Mathematica Asked on December 18, 2020
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 randomnumbers
where 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, randomnumbers
stores all the previously added values. What I would like to do is that once addition
is 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
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.
Answered by PanchoTheMacho on December 18, 2020
randomnumbers = {10};
For[w = 1, w <= 10, w++,
randomnumbers = {Last[randomnumbers], RandomInteger[10]};
addition = Total[randomnumbers];
Print[randomnumbers];
Print[addition]]
Answered by Chris Degnen on December 18, 2020
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}}
Answered by ubpdqn on December 18, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP