This code adds random digits to lists, and it works fine:
a = {{1}, {2}, {3}};
Do[
j = RandomInteger[{1, Length[a]}];
AppendTo[a[[j]], RandomInteger[9]];
Print[a], {i, 5}];
(* {{1,7},{2},{3}}
{{1,7},{2,2},{3}}
{{1,7},{2,2},{3,9}}
{{1,7},{2,2},{3,9,1}}
{{1,7,2},{2,2},{3,9,1}} *)
But if I replace the 'j' inside the [[]] with the definition j in the previous line, everything goes haywire:
a = {{1}, {2}, {3}};
Do[
AppendTo[a[[RandomInteger[{1, Length[a]}]]], RandomInteger[9]];
Print[a], {i, 5}];
(* {{1},{1,7},{3}}
{{1},{1,7},{1,4}}
{{1,7},{1,7},{1,4}}
{{1,7},{1,7},{1,7,9}}
{{1,7,9},{1,7},{1,7,9}} *)
Is this a bug or something I'm doing wrong?
a = {{1}, {2}, {3}}
; after the first step of appending it's{{1},{1,7},{3}}
- you append7
to{2}
and get{1,7}
. – corey979 yesterdayRandomInteger[{1, Length[a]}]
is evaluated twice in the second case. I will write a quick answer. – march yesterdayBlockRandom
; that is, as an alternative to your first approach you could also useDo[AppendTo[a[[BlockRandom[RandomInteger[{1, Length[a]}]]]], RandomInteger[9]]; Print[a], {i, 5}];
– kglr yesterday