Writing a C++ version of the algebra game 24

前端 未结 7 1507
离开以前
离开以前 2021-01-02 12:48

I am trying to write a C++ program that works like the game 24. For those who don\'t know how it is played, basically you try to find any way that 4 numbers can total 24 th

相关标签:
7条回答
  • 2021-01-02 13:46

    If you are allowed to use the same operator twice, you probably don't want to mix the operators into the numbers. Instead, perhaps use three 0's as a placeholder for where operations will occur (none of the 4 numbers are 0, right?) and use another structure to determine which operations will be used.

    The second structure could be a vector<int> initialized with three 1's followed by three 0's. The 0's correspond to the 0's in the number vector. If a 0 is preceded by zero 1's, the corresponding operation is +, if preceded by one 1, it's -, etc. For example:

    6807900 <= equation of form ( 6 @ 8 ) @ ( 7 @ 9 )
    100110 <= replace @'s with (-,-,/)
    possibility is (6-8)-(7/9)
    

    Advance through the operation possibilities using next_permutation in an inner loop.

    By the way, you can also return early if the number-permutation is an invalid postfix expression. All permutations of the above example less than 6708090 are invalid, and all greater are valid, so you could start with 9876000 and work your way down with prev_permutation.

    0 讨论(0)
提交回复
热议问题