1
$\begingroup$

I have the following lines of code:

randomnumbers = {10};
For[w = 1, w <= 10, w++,
 randomnumbers = Append[randomnumbers, RandomInteger[10]];
 addition = Last[randomnumbers] + Last[Drop[randomnumbers, -1]];
 
 
 Print[randomnumbers];
 Print[addition]
 ]

Basically, I have a list given by randomnumberswhere the first number is 10. Every iteration of the loop adds a random integer between 0 - 10 to randomnumbers. Once that number is added, I then do addition and I add the newly appended number to the number immediately before it. The issue is that every time the loop runs, randomnumbersstores all the previously added values. What I would like to do is that once additionis performed, the number in position 1 of randomnumbers is dropped. That way at any one time, there are only a max of two numbers in the list made by randomnumbers the newly appended number and the one immediately before it.

As it currently runs the outputs look something like this:

{10,1}
11
{10,1,2}
3
{10,1,2,5}
7
etc

but I would like an output that runs like what I've written below, where the list is not continuously increasing.

{10,1}
11
{1,2}
3
{2,5}
7
etc

I have tried adding in Drop[randomnumbers,1]after addition, but that doesn't seem to continuously remove the number in position 1 of randomnumbers

$\endgroup$
1
  • $\begingroup$ Have you tried randomnumbers = Drop[randomnumbers,1]? $\endgroup$ Jul 29, 2020 at 20:03

3 Answers 3

3
$\begingroup$
randomnumbers = {10};
For[w = 1, w <= 10, w++,
 randomnumbers = {Last[randomnumbers], RandomInteger[10]};
 addition = Total[randomnumbers];
 Print[randomnumbers];
 Print[addition]]
$\endgroup$
1
  • $\begingroup$ Wow, that's neat! $\endgroup$ Jul 30, 2020 at 3:02
0
$\begingroup$

The answer you are looking for is this one:

randomnumbers = {10};
For[w = 1, w <= 10, w++,
 If[w > 1, randomnumbers = Drop[randomnumbers, 1];
  randomnumbers = Append[randomnumbers, RandomInteger[10]];, 
  randomnumbers = Append[randomnumbers, RandomInteger[10]];];
 addition = Last[randomnumbers] + Last[Drop[randomnumbers, -1]];
 Print[randomnumbers]; Print[addition]]

P.S. I don't know yet how to properly write a code as an answer, I apologize for that, it is my second day using StackExchange forums.

$\endgroup$
0
$\begingroup$

Note you could this with NestList, e.g.

fun[n_] := 
 With[{s = Rest[NestList[{#[[2]], RandomInteger[10]} &, {0, 10}, n]]},
  Thread[{s, Total /@ s}]]

A list of 10 fun[10]:

{{{10, 0}, 10}, {{0, 7}, 7}, {{7, 6}, 13}, {{6, 1}, 7}, {{1, 7},
8}, {{7, 6}, 13}, {{6, 6}, 12}, {{6, 10}, 16}, {{10, 10}, 20}, {{10, 3}, 13}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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