Five programming problems every Software Engineer should be able to solve in less than 1 hour
Geoff Canyon
gcanyon at gmail.com
Sat May 9 19:51:58 EDT 2015
Problem 5
Write a program that outputs all possibilities to put + or - or nothing
between the numbers 1, 2, ..., 9 (in this order) such that the result is
always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
function sumPermute S,T
repeat
put offset(",",line 1 of S) into F
put F into fld 1
wait 0 ticks
if F = 0 then exit repeat
put empty into newS
repeat with i = 1 to 3
put char i of "+- " into C
repeat for each line L in S
put C into char F of L
put L & cr after newS
end repeat
end repeat
put char 1 to -2 of newS into S
end repeat
repeat for each line L in S
replace space with empty in L
if value(L) = T then put L & cr after R
end repeat
return R
end sumPermute
Test Input
put sumPermute("1,2,3,4,5,6,7,8,9",100) into fld 1
Test Output
1+23-4+56+7+8+9
12+3-4+5+67+8+9
1+2+34-5+67-8+9
1+2+3-4+5+6+78+9
123-4-5-6-7+8-9
123+45-67+8-9
1+23-4+5+6+78-9
12-3-4+5-6+7+89
12+3+4+5-6-7+89
123-45-67+89
123+4-5+67-89
More information about the use-livecode
mailing list