It's because each time you Count
(that is, for each element of Range[6]
) you're creating a new array of RandomInteger
s to Count
. Rewriting your Table
just as a RandomInteger
list, consider
SeedRandom[1]
Count[RandomInteger[{1, 6}, 10], #] & /@ {3, 3, 3, 3, 3, 3}
By your reasoning, this should produce the same number six times -- however many threes there are in the RandomInteger
array. But what it actually produces is
(* {2, 1, 1, 1, 1, 3} *)
because each time Count[RandomInteger[{1, 6}, 10], #] &
evaluates, it's generating a new array.
Try a different approach, and create your random array first:
SeedRandom[1]
rand = RandomInteger[{1, 6}, 10];
Count[rand, #] & /@ {3, 3, 3, 3, 3, 3}
Count[rand, #] & /@ Range[6] // Total
(* {2, 2, 2, 2, 2, 2} *)
(* 10 *)
as expected.
As people have pointed out, Map
ping Count
over a Range
looks like you might be trying to get the functionality of Counts
, which counts up how many times a particular element appears in the list. So, on the previous example:
KeySort@Counts[rand]
(* <|1 -> 5, 2 -> 1, 3 -> 2, 5 -> 2|> *)
and Total
works just the same:
Total @ %
(* 10 *)
Table[RandomInteger[{1, 6}], {i, 10}]
is being evaluated six times, and is different in each instance. UseTally[]
orCounts[]
instead. $\endgroup$With[{table=Table[RandomInteger[{1, 6}], {i, 10}]}, Count[table, #] & /@ Range[6]//Total]
, though I'd really useCounts
. $\endgroup$