# Golf Recamán's sequence

조회 수: 2(최근 30일)
John Doe 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?

로그인 to comment.

### 답변(1개)

George Iskander 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

#### 댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by