4
$\begingroup$

I code the following to count events.

Count[Table[RandomInteger[{1, 6}], {i, 10}], #] & /@ Range[6]//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.

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

1 Answer 1

8
$\begingroup$

It's because each time you Count (that is, for each element of Range[6]) you're creating a new array of RandomIntegers 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, 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 *)
$\endgroup$
1
  • $\begingroup$ I got it. Thank you very much. $\endgroup$
    – yaykhel
    Nov 5, 2017 at 11:40

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.