简体   繁体   中英

Generate all sum combinations

Given a set of 6 numbers eg 1,5,8,9,2,6 and 2 operands eg + and - i was wondering how you would go about generating all possible valid sums eg 1+8=9 and so on.

The numbers could be an positive number 0-9 and the operands could be +-/* squared and Square Root

If any one can help i would really appreciate it.

Thanks

since it is a set, and the range of numbers is [0,9] - a trivial solution will be backtracking, requiring 3^n < 3^10 iterations at most. just iterate over all possibilities (each element can be in/out of the list, and all possibilities to 'connect' between two elements. for unary oparations: with it/ with out it).
pseudo code:

solution(set,aFormula,op1,op2):
  if set == []: print calculate(aFormula)
  else:
     solution(set[1-set.end],aForumula,op1,op2)
     solution(set[1-set.end],op1(aFormula,set[0]),op1,op2)
     solution(set[1-set.end],op2(aFormula,set[0]),op1,op2)

note - you might need an extra handling for the unary operations, but it will not change the algorithm much.

"positive number 0-9"

0 is not a positive number.

"the operands could be +-/* squared and Square Root"

The square and the square root do only take one parameter, so how do you apply this over two elements of your list?

As you didn't specify any language here the solution for the addition as stated in your post:

a = [1, 5, 8, 9, 2, 6]
print set ( [x + y for x in a for y in a] )

This allows sums of the same element with itself, if this behaviour is not intended, change it accordingly. Use other operators as needed.

Very verbose example in C:

#include <stdio.h>

void main ()
{
    int list [6] = {1,5,8,9,2,6};
    int i, j;
    for (i = 0; i < 6; i++)
        for (j = i + 1; j < 6; j++)
            printf ("%d + %d = %d\n", list [i], list [j], list [i] + list [j] );
}

well, since there are only 6*5*4 (picking numbers from the set) *4 (operands), you could easily generate all possible permutations and check each for validity. I cannot provide code in objective c, but you could just use nested loops to get all possible permutations, perform the computation and print the permutation if the result of the computation matches the number you picked as "result" in the permutation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM