Instantly share code, notes, and snippets.

# wo0dyn/Math-Puzzle.md

Last active August 9, 2018 03:01
Show Gist options
• Save wo0dyn/05601fef3666bf4ff52604ecabbba37c to your computer and use it in GitHub Desktop.

# Math Puzzle

## One possible solution: brute force

```import collections
import itertools

def check(numbers, code):
"""
Compute correct numbers and numbers in the wrong position.

>>> check([1, 2, 3], [1, 2, 3])
(3, 0)
>>> check([3, 2, 1], [1, 2, 3])
(1, 2)
>>> check([3, 1, 2], [1, 2, 3])
(0, 3)
>>> check([4, 5, 6], [1, 2, 3])
(0, 0)
"""

stats = collections.Counter()
for index, number in enumerate(numbers):
if number == code[index]:
stats['correct'] += 1
elif number in code:
stats['wrong-position'] += 1

return stats['correct'], stats['wrong-position']

for code in itertools.product(range(10), repeat=3):
# Testing (0, 0, 0), (0, 0, 1), …, (9, 9, 9)
try:
assert check(code, [2, 9, 1]) == (1, 0)
assert check(code, [2, 4, 5]) == (0, 1)
assert check(code, [4, 6, 3]) == (0, 2)
assert check(code, [5, 7, 8]) == (0, 0)
assert check(code, [5, 6, 9]) == (0, 1)
except AssertionError:
continue
else:
print(f'Code is {code}')```
```\$ python3 puzzle.py
Code is (3, 9, 4)```