## Kakuro combinations

The Japanese game Kakuro is not as popular or well known as Sudoku, but it’s still a fun puzzle. If you are not familiar with it, you can check Wikipedia’s explanation here.

This is an example of a solved Kakuro and sometimes it’s handy knowing all the possible 5-factor combinations that sum 27 for example.

In this example, the following 5-factor combinations exist:

- 1 + 2 + 7 + 8 + 9
- 1 + 3 + 6 + 8 + 9
- 1 + 4 + 5 + 8 + 9
- 1 + 4 + 6 + 7 + 9
- 1 + 5 + 6 + 7 + 8
- 2 + 3 + 5 + 8 + 9
- 2 + 3 + 6 + 7 + 9
- 2 + 4 + 5 + 7 + 9
- 2 + 4 + 6 + 7 + 8
- 3 + 4 + 5 + 6 + 9
- 3 + 4 + 5 + 7 + 8

Since I’m a Kakuro beginner, I decided to code a very simple script to get all possible combinations, so let’s see what we can do in Python.

```
import itertools
import collections
from functools import reduce
KakuroData = collections.namedtuple('KakuroData', 'sum length factors')
combinations: List['KakuroData'] = []
def find_combinations():
# we get all the possible combinations that have 2 to 9 factors
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for length in range(2, 10):
for combination in itertools.combinations(numbers, length):
total_sum = sum(combination)
factors_str = "".join(map(str, combination))
data = KakuroData(sum=total_sum, length=length, factors=factors_str)
combinations.append(data)
combinations.sort()
```

As you can see, the itertools package comes with a useful way to get all combinations of certain length from a list. Then we calculate the sum and concatenate the factors using functional programming.

Alternatively, this is another way of doing it:

```
def find_combinations2():
# we get all the possible combinations that have 2 to 9 factors
for length in range(2, 10):
for combination in itertools.combinations('123456789', length):
# reduce iterates through a collection and shortens it by applying a function to the two first elements,
# then applies the same function to the result and the next element
total_sum = reduce(lambda x, y: int(x) + int(y), combination)
factors_str = "".join(combination)
data = KakuroData(sum=total_sum, length=length, factors=factors_str)
combinations.append(data)
combinations.sort()
```

Finally, we need to output the information. As usual with formatting and styling, this part took me ten times more than getting the list of combinations ðŸ˜‰. The program produces the following HTML table.

There is also a monochrome alternative which might be better for printing purposes.

In case you want to customize the colors, you can get the source code here.

Thanks for reading!