unknown recursive method, must find how it runs - recursion

This was a past exam question and I have no idea what it does! Please can someone run through it.
public static int befuddle(int n){
if(n <= 1){
return n;
}else{
return befuddle(n - 1) * befuddle(n - 2) + 1;
}
}

this is computing the sequence: 0, 1, 1, 2, 3, 7, 22, 155, ...
Which can be expressed using this formula:
when dealing with numerical sequences, a great resources is The Online Encyclopedia of Integer Sequences!, a quick search there shows a similar sequence to yours but with:
giving the following sequence: 0, 0, 1, 1, 2, 3, 7, 22, 155, ...
you can find more about it here

public static is the type of member function it is. I'm assuming this is part of a class? The static keyword allows you to use it without creating an instance of the class.
Plug in a value of 'n' and step through it. For instance, if n = 1, then the function returns 1. If n = 0 -> 0; n = -100 -> -100.
If n = 2, the else branch is triggered and befuddled is called with 1 and 0. So n = 2 returns 0*1 + 1 = 1.
Do the same thing for n = 3, etc. (calls n = 2 -> 1, and n = 1 -> 1, so n=3 -> 1*1+1 = 2.)

Related

Get a sequence number from 0 and alternate positive/negative incrementing every other time

I would like to be able to obtain a (non-convergent) sequence of numbers by a simple calculation that would look like this: 0, 1, -1, 2, -2, 3, -3, 4, -4 ...
By simple calculation I mean being able to do it with a single variable that would start from 1 (or 0) without having to rearrange this sequence.
I made several (unsuccessful) attempts in Lua, here is what it should look like in principle (this example only alternates 0s and 1s):
do
local n = 0
for i = 1, 10 do print(n)
n = n==0 and 1 or -n + (n/n)
end
end
Is this possible and how?
Update:
I just succeeded like this:
local n, j = 0, 2
for i = 1, 10 do print(n)
n = n==0 and 1 or j%2==0 and -(n+(n/math.abs(n))) or -n
j = j + 1
end
But I have to help myself with a second variable, I would have liked to know if with only n it would be possible to do it?
The whole numbers are enumerable. Thus there exists a mapping from the natural numbers to whole numbers. You'll now have to use a loop to loop over natural numbers, then compute a function that gives you a whole number:
-- 0, 1...10, -1...-10 -> 21 numbers total
for n = 1, 21 do
local last_bit = n % 2
local sign = 1 - (2 * last_bit)
local abs = (n - last_bit) / 2
print(sign * abs)
end
prints
-0
1
-1
2
-2
...
10
-10
on Lua 5.1; on newer Lua versions, you can use n // 2 instead of (n - last_bit) / 2 to (1) use ints and (2) make extracting the abs cheaper.
Simply "emit" both n and -n in each iteration:
for n = 0, 10 do
print(n)
print(-n)
end
My problem was solved by #EgorSkriptunoff in comment of my question, his approach is:
n = (n > 0 and 0 or 1) - n
The output of:
local n = 0
for i=1,10 do io.write(n..", ")
n = (n > 0 and 0 or 1) - n
end
Actually gives:
0, 1, -1, 2, -2, 3, -3, 4, -4, 5,

Dependent Arrays in Constraints JuMP

I want to code this constraint.
d and a in the below code are the subsets of set S with the size of N. For example: (N=5, T=3, S=6), d=[1,2,2,3,1] (the elements of d are the first three digits of S and the size of d is N) and a=[6,4,5,6,4] (the elements of a are the three last digits of set S and the size of a is N).
In the constraint, s should start with d and end with a.
It should be like s[j=1]=1:6, s[j=2]=2:4, s[j=3]=2:5, s[j=4]=3:6, s[j=5]1:4.
I do not know how to deal with this set that depends on the other sets. Can you please help me to code my constraint correctly? The below code is not working correctly.
N = 5
T=3
S=6
Cap=15
Q=rand(1:5,N)
d=[1,2,2,3,1]
a=[6,4,5,6,4]
#variable(model, x[j=1:N,t=1:T,s=1:S], Bin)
#constraint(model, [j= 1:N,t = 1:T, s = d[j]:a[j]], sum(x[j,t,s] * Q[j] for j=1:N) <= Cap)
N, T, S = 5, 3, 6
Q = rand(1:5,N)
d = [1, 2, 2, 3, 1]
a = [6, 4, 5, 6, 4]
using JuMP
model = Model()
#variable(model, x[1:N, 1:T, 1:S], Bin)
#constraint(
model,
[t = 1:T, s = 1:S],
sum(x[j, t, s] * Q[j] for j in 1:N if d[j] <= s < a[j]) <= 15,
)
p.s. There's no need to post multiple comments and questions:
Coding arrays in constraint JuMP
You should also consider posting on the Julia discourse instead: https://discourse.julialang.org/c/domain/opt/13. It's easier to have a conversation there.

Most common term in a vector - PARI/GP

I feel like I'm being really stupid here as I would have thought there's a simple command already in Pari, or it should be a simple thing to write up, but I simply cannot figure this out.
Given a vector, say V, which will have duplicate entries, how can one determine what the most common entry is?
For example, say we have:
V = [ 0, 1, 2, 2, 3, 4, 6, 8, 8, 8 ]
I want something which would return the value 8.
I'm aware of things like vecsearch, but I can't see how that can be tweaked to make this work?
Very closely related to this, I want this result to return the most common non-zero entry, and some vectors I look at will have 0 as the most common entry. Eg: V = [ 0, 0, 0, 0, 3, 3, 5 ]. So whatever I execute here I would like to return 3.
I tried writing up something which would remove all zero terms, but again struggled.
The thing I have tried in particular is:
rem( v ) = {
my( c );
while( c = vecsearch( v, 0 ); #c, v = vecextract( v, "^c" ) ); v
}
but vecextract doesn't seem to like this set up.
If you can ensure all the elements are within the some fixed range then it is enough just to do the counting sorting with PARI/GP code like this:
counts_for(v: t_VEC, lower: t_INT, upper: t_INT) = {
my(counts = vector(1+upper-lower));
for(i=1, #v, counts[1+v[i]-lower]++);
vector(#counts, i, [i-1, counts[i]])
};
V1 = [0, 1, 2, 2, 3, 4, 6, 8, 8, 8];
vecsort(counts_for(V1, 0, 8), [2], 4)[1][1]
> 8
V2 = [0, 0, 0, 0, 3, 3, 5];
vecsort(counts_for(V2, 0, 5), [2], 4)[1][1]
> 0
You also can implement the following short-cut for the sake of convenience:
counts_for1(v: t_VEC) = {
counts_for(v, vecmin(v), vecmax(v))
};
most_frequent(v: t_VEC) = {
my(counts=counts_for1(v));
vecsort(counts, [2], 4)[1][1]
};
most_frequent(V1)
> 8
most_frequent(V2)
> 0
The function matreduce provides this in a more general setting: applied to a vector of objects, it returns a 2-column matrix whose first column contains the distinct objects and the second their multiplicity in the vector. (The function has a more general form that takes the union of multisets.)
most_frequent(v) = my(M = matreduce(v), [n] = matsize(M)); M[n, 1];
most_frequent_non0(v) =
{ my(M = matreduce(v), [n] = matsize(M), x = M[n, 1]);
if (x == 0, M[n - 1, 1], x);
}
? most_frequent([ 0, 1, 2, 2, 3, 4, 6, 8, 8, 8 ])
%1 = 8
? most_frequent([x, x, Mod(1,3), [], [], []])
%2 = []
? most_frequent_non0([ 0, 0, 0, 0, 3, 3, 5 ])
%3 = 5
? most_frequent_non0([x, x, Mod(1,3), [], [], []])
%4 = x
The first function will error out if fed an empty vector, and the second one if there are no non-zero entries. The second function tests for "0" using the x == 0 test (and we famously have [] == 0 in GP); for a more rigorous semantic, use x === 0 in the function definition.

Best way to identify duplicates in two lists or a dictionary?

Lets say you have two lists such as:
list1 = [-2, -1, 0, 1, 2, 3]
list2 = [4, 1, 0, 1, 4, 9]
...and the two lists were zipped into a dictionary to produce:
dict1 = {-2: 4,
-1: 1,
0: 0,
1: 1,
2: 4,
3: 9}
...where list1 is the key, and list 2 is the value.
You will notice that some of the elements in list2 are duplicates such as 4 and 1. They show up twice in list 2, and consequently in the dictionary.
-2 corresponds to 4
2 corresponds to 4
-1 corresponds to 1
1 corresponds to 1
I am trying to figure out a way either using the lists or the dictionary to identify the duplicate items in list2, and return their keys from list 1.
So the returned values I would expect from the two lists above would be:
(-2, 2) #From list 1 since they both correspond to 4 in list2
(-1, 1) #from list 1 since they both correspond to 1 in list2
In this example, list2 happens to be the square of list1. But this will not always be the case.
So ultimately, what I am looking for is a way to return those keys based on their duplicate values.
Any thoughts on how to approach this? I am able to identify the duplicates in list2, but I am completely stuck on how to identify their corresponding values in list 1.
In python3:
from itertools import groupby
list1 = [-2, -1, 0, 1, 2, 3]
list2 = [4, 1, 0, 1, 4, 9]
pairs = zip(list2, list1)
ordered = sorted(pairs, key=lambda x: x[0])
groups = ((k, list(g)) for k,g in groupby(ordered, key=lambda x: x[0])) # generator
duplicates = (k for k in groups if len(k[1])>1) # generator
for k,v in duplicates :
print(str(k) + " : " + str(list(v)))
result:
1 : [(1, -1), (1, 1)]
4 : [(4, -2), (4, 2)]
Bonus: in functional c#:
var list1 = new[] { -2, -1, 0, 1, 2, 3 };
var list2 = new[] { 4, 1, 0, 1, 4, 9 };
var g = list1.Zip(list2, (a, b) => (a, b)) //create tuples
.GroupBy(o => o.b, o => o.a, (k, group) => new { key = k, group = group.ToList() }) //create groups
.Where(o => o.group.Count > 1) // select group with minimum 2 elements
.ToList(); // no lazy
foreach (var kvp in g)
Console.WriteLine($"{kvp.key}: {string.Join(",", kvp.group)}");
result:
4: -2,2
1: -1,1

Does there exist an iterative implementation of fibonacci that is not a tabulation?

All the iterative implementations that I have found seem to necessarily be using a tabulation method.
Is dynamic programming an alternative only to recursion, while it is a mandatory solution for iteration?
An iterative implementation of fibonacci that does not use tabulation, memoization, or a swap variable – this code from my answer here on getting hung-up learning functional style.
const append = (xs, x) =>
xs.concat ([x])
const fibseq = n => {
let seq = []
let a = 0
let b = 1
while (n >= 0) {
n = n - 1
seq = append (seq, a)
a = a + b
b = a - b
}
return seq
}
console.log (fibseq (500))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... ]
And remember, procedure differs from process – ie, recursive procedures can spawn iterative processes. Below, even though fibseq is defined recursively, the process that it spawns is iterative – again, no tabulation, memoization, or any other made-up terms going on
const recur = (...values) =>
({ type: recur, values })
const loop = f =>
{
let acc = f ()
while (acc && acc.type === recur)
acc = f (...acc.values)
return acc
}
const fibseq = x =>
loop ((n = x, seq = [], a = 0, b = 1) =>
n === 0
? seq.concat ([a])
: recur (n - 1, seq.concat ([a]), a + b, a))
console.time ('loop/recur')
console.log (fibseq (500))
console.timeEnd ('loop/recur')
// [ 0,
// 1,
// 1,
// 2,
// 3,
// 5,
// 8,
// 13,
// 21,
// 34,
// ... 490 more items ]
// loop/recur: 5ms
There is a definition of Fibonacci numbers as a sum of binomial coefficients, which themselves can be calculated iteratively, as a representation of all the compositions of (n-1) from 1s and 2s.
In Haskell, we could write:
-- https://rosettacode.org/wiki/Evaluate_binomial_coefficients#Haskell
Prelude> choose n k = product [k+1..n] `div` product [1..n-k]
Prelude> fib n = sum [(n-k-1) `choose` k | k <- [0..(n-1) `div` 2]]
Prelude> fib 100
354224848179261915075

Resources