# Count does not tally with total

I code the following to count events.

Count[Table[RandomInteger[{1, 6}], {i, 10}], #] & /@ Range//Total


By right, if I total, I expect 10. Sometimes it gives < 10, sometimes more than 10.

I want to generate a random number between 1 and 6 and wanted to how many time count each occurs.

Thank you.

• Table[RandomInteger[{1, 6}], {i, 10}] is being evaluated six times, and is different in each instance. Use Tally[] or Counts[] instead. – J. M.'s discontentment Nov 5 '17 at 11:12
• Or With[{table=Table[RandomInteger[{1, 6}], {i, 10}]}, Count[table, #] & /@ Range//Total], though I'd really use Counts. – jjc385 Nov 5 '17 at 11:14

It's because each time you Count (that is, for each element of Range) you're creating a new array of RandomIntegers to Count. Rewriting your Table just as a RandomInteger list, consider

SeedRandom
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
rand = RandomInteger[{1, 6}, 10];

Count[rand, #] & /@ {3, 3, 3, 3, 3, 3}
Count[rand, #] & /@ Range // Total

(* {2, 2, 2, 2, 2, 2} *)

(* 10  *)


as expected.

As people have pointed out, Mapping 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 *)

• I got it. Thank you very much. – yaykhel Nov 5 '17 at 11:40