3
$\begingroup$

I hope to get a list whose elements decrease by $2$ or increase by $1$, in turn, until the last element is $0$. For instance, starting with $4$ the sequence would be {4, 2, 3, 1, 2, 0}. If you gave me $5$ instead, the sequence would be {5, 3, 4, 2, 3, 1, 2, 0}.

This is my current method:

i = 1;
NestWhileList[If[++i; EvenQ[i], # - 2, # + 1]&, 5, UnequalTo[0]]

{5, 3, 4, 2, 3, 1, 2, 0}

But I am not very satisfied with that intermediate variable i. I would like to find other methods.

$\endgroup$
5
$\begingroup$
f = FoldList[Plus, #, {-2, 1}[[Mod[Range[2 # - 3], 2, 1]]]] &

f @ 5

{5, 3, 4, 2, 3, 1, 2, 0}

f @ 4

{4, 2, 3, 1, 2, 0}

$\endgroup$
4
$\begingroup$

A combination of Range and Riffle produces the desired result.

sequence[n_Integer] := Riffle[Range[n, 2, -1], Range[n - 2, 0, -1]]

Applying to 5

sequence[5]
(* {5, 3, 4, 2, 3, 1, 2, 0} *)
$\endgroup$
  • $\begingroup$ The answer can solve this problem,I have thought it here.But I don't like it still,because that two alternate function(#-2& and #+1&) can be more complicate function.Then this method will be run out. $\endgroup$ – yode Feb 11 '17 at 17:53
1
$\begingroup$
seq[n_ /; n > 1] := Reverse[Riffle[Range[0, n - 2], Range[2, n]]]
seq[6]

{6, 4, 5, 3, 4, 2, 3, 1, 2, 0}

$\endgroup$
1
$\begingroup$
f[{x_, y_}] := {x + 1 - 3 Mod[y, 2], y + 1}
func[a_] := NestWhileList[f, {a, 1}, #[[1]] != 0 &][[All, 1]]

e.g.func[10] yields:

{10, 8, 9, 7, 8, 6, 7, 5, 6, 4, 5, 3, 4, 2, 3, 1, 2, 0}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.