4
$\begingroup$

I am interested in replicating the code in this question on MSE, whose contents I have copied for ease of reading:

Pseudocode:
Consider that 1 is the starting index of a list

1.  input natural number n.
2.  let s = list of all natural numbers {1, 2, 3, 4, 5, 6 ...}
3.  while (n>1) do
    3.1.  drop each n-th elementh from s
    3.2.  for int i = 2 to ∞ do s[i] += s[i-1]
    3.3.  n = n-1
4.  Now s = {1n, 2n, 3n, 4n ...}


Example: n = 3
s = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...}

perform 3.1:  s = {1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16...}
perform 3.2:  s = {1, 3, 7, 12, 19, 27, 37, 48, 61, 75, 91 ...}
perform 3.3:  n = 2 > 1

perform 3.1:  s = {1, 7, 19, 37, 61, 91 ...}
perform 3.2:  s = {1, 8, 27, 64, 125, 216 ...}
perform 3.3:  n = 1 => end of while loop

The final state of s is {13, 23, 33, 43, 53 ...}


My interpretation of it is

fn[nu_][{o_, a_}] := {# - 1, Delete[a, #]} &@Mod[nu + o, Length@a, 1]
ff[n_, w_] := Last@NestList[fn[n], {0, w}, Floor[Length@w/n]][[All, 2]]
f1[l_] := Table[Total[Take[l, a]], {a, 1, Length@l}]

setting range=$n^2$

n = 4; list = Range@(n^2);
NestList[{#[[1]] - 1, f1[ff[#[[1]], #[[2]]]]} &, {n, list}, n - 1][[All, 2]] 
// ColumnForm

but my question is, how would this be written in Mathematica in the form of the pseudocode given by John_devou in the original question?

$\endgroup$
5
$\begingroup$

Something like this:

f[n_] := Module[{s, i},
  i = n;
  s = Range[1000];
  While[i > 1,
   s = Drop[s, {i, Length@s, i}];
   s = Accumulate@s;
   i--;
   ];
  s
  ]

f[3]

{1, 8, 27, 64, 125, 216, 343,...}

If I was trying to leverage Mathematica I might have written:

s = Range[1000];
n = 3;
Fold[Accumulate@Drop[#, {#2, Length@#, #2}] &, s, Reverse@Rest@Range@n]
$\endgroup$
  • $\begingroup$ is it possible to display the loop stages with both of these methods, as given in the NestList example in the question? $\endgroup$ – martin Nov 22 '14 at 10:41
  • 1
    $\begingroup$ @martin Sure, you can Sow the information you want to save in the While loop for example. In the latter solution you can also use Sow, or if you don't need the intermediate step 3.1 you may simply change Fold to FoldList. $\endgroup$ – C. E. Nov 22 '14 at 11:12
  • $\begingroup$ great - thak you for your help :) $\endgroup$ – martin Nov 22 '14 at 11:27

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.