Golf Recamán's sequence

조회 수: 1 (최근 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에서 Audio and Video Data에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by