Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a math algorithm for an equation

I just post a mathematic question at math.stackexchange, but I'll ask people here for a programmatically recursive algorithm.

The problem: fill in the blank number from 1 to 9 (once and only once each blank) to finish the equation.

problem

Additional conditions:

1. Mathematic priority DOES matter. 
2. All numbers (include evaluation result) should be integers.
Which mean the divide should be divisible (E.g. 9 mod 3 = 0 is OK, 8 mod 3 != 0 is not OK).
3. For those who don't know (as one in the original question), the operations in the diagram are: 
+ = plus; : = divide; X = multiple; - = minus.

There should be more than 1 answer. I'd like to have a recursive algorithm to find out all the solutions.

Original question

PS: I'd like to learn about the recursive algorithm, performance improval. I was trying to solve the problem using brute force. My PC freeze for quite a while.

like image 806
Eddie Avatar asked Jun 05 '26 16:06

Eddie


1 Answers

You have to find the right permuations

9! = 362880

This is not a big number and you can do your calculations the following way:

isValid(elements)
    //return true if and only if the permutation of elements yields the expected result
end isValid

isValid is the validator, which checks whether a given permutation is correct.

calculate(elements, depth)
    //End sign
    if (depth >= 9) then
        //if valid, then store
        if (isValid(elements)) then
            store(elements)
        end if
        return
    end if
    //iterate elements
    for element = 1 to 9
        //exclude elements already in the set
        if (not contains(elements, element)) then
            calculate(union(elements, element), depth + 1)
        end if
    end for
end calculate

Call calculate as follows:

calculate(emptySet, 1)
like image 154
Lajos Arpad Avatar answered Jun 08 '26 06:06

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!