Golf Recamán's sequence

2 次查看(过去 30 天)
John Doe
John Doe 2014-9-23
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?

回答(1 个)

George Iskander
George Iskander 2020-2-5
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

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by