10-05-2011, 17:37
IT'S A TRAP!
Write a function "void noparens(char *expression)" that prints all the possible different results you can get from different grouping of parentheses in the given expression.
The string 'expression' contains the operators '+', '-', '*' and positive integers (or possibly no operators and just one integer). The expression is entirely unparenthesized. Your function should determine the result of every possible parenthesization of the expression and print the distinct ones.
Don't worry about overflowing int or strange formatting of the expression.
Examples:
A. expression "1 + 2 - 3 * 4"
(((1 + 2) - 3) * 4) = 0
((1 + 2) - (3 * 4)) = -9
((1 + (2 - 3)) * 4) = 0
(1 + ((2 - 3) * 4)) = -3
(1 + (2 - (3 * 4))) = -9
There were five possible, but two were the same, so your function should print:
3 unique { 0, -9, -3 }
B. expression "1 - 1 + 1"
((1 - 1) + 1) = 1
(1 - (1 + 1)) = -1
Your function should print:
2 unique { 1, -1 }
C. expression "10"
1 unique { 10 }
D. expression "1 + 2 + 3 * 4 - 5 * 2"
18 unique { 38, 14, -12, -36, 20, 5, 17, 0, -3, -15, 32, 11, 31, -8, -9, -29, 19, -1 }
Write a function "void noparens(char *expression)" that prints all the possible different results you can get from different grouping of parentheses in the given expression.
The string 'expression' contains the operators '+', '-', '*' and positive integers (or possibly no operators and just one integer). The expression is entirely unparenthesized. Your function should determine the result of every possible parenthesization of the expression and print the distinct ones.
Don't worry about overflowing int or strange formatting of the expression.
Examples:
A. expression "1 + 2 - 3 * 4"
(((1 + 2) - 3) * 4) = 0
((1 + 2) - (3 * 4)) = -9
((1 + (2 - 3)) * 4) = 0
(1 + ((2 - 3) * 4)) = -3
(1 + (2 - (3 * 4))) = -9
There were five possible, but two were the same, so your function should print:
3 unique { 0, -9, -3 }
B. expression "1 - 1 + 1"
((1 - 1) + 1) = 1
(1 - (1 + 1)) = -1
Your function should print:
2 unique { 1, -1 }
C. expression "10"
1 unique { 10 }
D. expression "1 + 2 + 3 * 4 - 5 * 2"
18 unique { 38, 14, -12, -36, 20, 5, 17, 0, -3, -15, 32, 11, 31, -8, -9, -29, 19, -1 }