/now
projects
ramblings
smol projects

combinations

12.11.2023 1 min read

Create a function that takes a variable number of arguments, each argument representing the number of items in a group. The function should return the number of permutations (combinations) of choices you would have if you selected one item from each group.

combinations(2, 3) ➞ 6

combinations(3, 7, 4) ➞ 84

combinations(2, 3, 4, 5) ➞ 120

In crystal, we can use the splat operator (*):

def combinations(*items)
  items.reject(0).reduce { |a, b| a * b }
end

In nim, we have varargs:

func combinations(args: varargs[int]): int =
    args.filterIt(it != 0).foldl(a * b)

In raku, we don’t even need to provide a function signature - we can use the @_ variable, which contains all the arguments we pass in:

sub combinations {
    [*] @_.grep({$_.so});
}

Finally, js/ts:

function combinations(...items: number[]) {
  return items.reduce((acc, curr) => (curr ? acc * curr : acc), 1);
}

In js, we don’t need the function signature either - we can just use ...arguments. But, we do what we need to make the Typescript compiler happy 🤷‍♂

Built with Astro and Tailwind 🚀