Recamán's sequence described in pseudo-code is as follows:
A(0) = 0
A(n) = A(n-1) - n if A(n-1) - n > 0 and is new, else
A(n) = A(n-1) + n
The 11 first elements is:
0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11
As a challenge, I should write a function that outputs the first n elements, in as few characters as possible, where the number of elements to display should be used as input to the function. The best I can do is 90 characters:
function A=f(n)
A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end
(written out):
function A = Recamans(n)
A = zeros(1,n);
A(1) = 0;
for ii = 1:n-1
b = A(ii)-ii;
A(ii+1) = b + 2*ii;
if b > 0 && ~any(A == b)
A(ii + 1) = b;
end
end
end
MY question is: Is it possible to do this in fewer characters in MATLAB?