Golf Recamán's sequence

3 views (last 30 days)
John Doe
John Doe on 23 Sep 2014
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?

Answers (1)

George Iskander
George Iskander on 5 Feb 2020
function x=Recaman_seq(n)
x=zeros(1,n);
for ii=2:length(x)
p=x(ii-1)-ii+1;
if (all(x~=p) && p>0)
x(ii)=p
else
x(ii)=x(ii-1)+ii-1
end
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!