Order of Operations Game Solution

97 Views Asked by At

My AP Computer Science teacher likes to play a game with his students where he writes 4 random numbers on the board and a fifth, target number. The objective is to use the four basic operations (+,−,×,÷) to get the target number. Each number can only be used once, but the operations can be reused. Order of operations does apply, and the numbers can be reordered.

Ex: Given the numbers 6 9 5 4, get to 50

Solution: (9 + 5) × 4 - 6 = 50

My teacher and I are looking for a way to find the solution(s) to a set of 5 numbers with a computer program. Because there are 24 arrangements of 4 numbers and 24 ways to arrange the 4 operations, there are 576 potential solutions to check, so brute force is not exactly easy.

1

There are 1 best solutions below

5
On BEST ANSWER

You are given $4$ numbers, and a target. There are $4!$ ways to arrange the $4$ numbers. There $4^3$ ways to add an operation between two numbers. Then, there are $8$ distinct ways to add parentheses to group numbers (this may be redundant over multiplication or division, but it does not add that much more to the computation time). This means there are $4!\cdot4^3\cdot8=12288$ possibilities for the computer to check, which should take about one to two seconds maximum.

Some pseudocode for this would have some data structure (Array, or an equivalent) with 15 cells to hold all possible combinations of numbers, operations, and parentheses, with an iterator like a for loop running through and testing all possible arrangements. I know this is a little oversimplified, but programming isn't my strong suit and I would appreciate it if someone with a little more experience could add something more substantial.