Skip to content
Advertisement

All tuples of positive integers

How do I create a generator that will return tuples of all combinations of positive integers, example for generating triplets.

JavaScript

Advertisement

Answer

This code uses a similar approach to Paul Hankin’s, but it’s more general since it will generate tuples of any desired width, not just 3.

JavaScript

output

JavaScript

The algorithm for compositions was derived from the technique used for counting the number of compositions explained in the Wikipedia article on compositions. This is essentially a variation of the well-known Stars and Bars technique.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement