3
$\begingroup$

Consider the following input:

ClearAll[dice, sides];
dice := 3
sides := 6
CountsBy[Times @@@ Tuples[Range[1, sides], dice], {1, sides^dice}]

This gives the output

<|{1,216}\[InvisibleApplication](1)->1,
  {1,216}\[InvisibleApplication](2)->3,
  {1,216}\[InvisibleApplication](3)->3,
  {1,216}\[InvisibleApplication](4)->6,
  {1,216}\[InvisibleApplication](5)->3,
  {1,216}\[InvisibleApplication](6)->9,
  {1,216}\[InvisibleApplication](8)->7,
  {1,216}\[InvisibleApplication](10)->6,
  {1,216}\[InvisibleApplication](12)->15,
  {1,216}\[InvisibleApplication](9)->3,
  {1,216}\[InvisibleApplication](15)->6,
  ...

That is acceptable but I would like the output to be sorted after the values that I multiply, i.e., I would like the number of times the product is 9 to be printed between the number of times the product is 8 and the number of times the product is 10. That is, I would like the output to be

<|{1,216}\[InvisibleApplication](1)->1,
  {1,216}\[InvisibleApplication](2)->3,
  {1,216}\[InvisibleApplication](3)->3,
  {1,216}\[InvisibleApplication](4)->6,
  {1,216}\[InvisibleApplication](5)->3,
  {1,216}\[InvisibleApplication](6)->9,
  {1,216}\[InvisibleApplication](8)->7,
  {1,216}\[InvisibleApplication](9)->3,
  {1,216}\[InvisibleApplication](10)->6,
  {1,216}\[InvisibleApplication](12)->15,
  {1,216}\[InvisibleApplication](15)->6,
  ...

but how do I get this?

P.S. The "problem" occures several times later in the output list, too.

$\endgroup$
3
$\begingroup$

If you have those entries sorted then the result will be sorted too:

CountsBy[
    Sort[Times @@@ Tuples[Range[1, sides], dice]]
  , {1, sides^dice}
]

but the fastest would probably be just a KeySort:

KeySort @ CountsBy[
    Times @@@ Tuples[Range[1, sides], dice]
  , {1, sides^dice}
]
$\endgroup$
2
$\begingroup$

I personally prefer @Kuba's method of KeySort. You can always use Normalthen SortBy and then Association

ClearAll[dice, sides];
dice := 3
sides := 6
<| SortBy[First]@Normal@CountsBy[
Times @@@ Tuples[Range[1, sides], dice], {1, sides^dice}] |>
$\endgroup$
  • $\begingroup$ You know you can express your preferences by upvoting answers :) $\endgroup$ – Kuba Mar 20 '17 at 18:59
  • $\begingroup$ @Kuba +1 for the comment :) $\endgroup$ – Ali Hashmi Mar 20 '17 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.