If I have a list of unknown numbers between 1 & 9.
For example:
set theList to {1, 2, 3, 5, 7, 9}
…and an unknown number between 1 & 12,
For example:
set targetNumber to 12
Is there a simple routine to see if any of the numbers in theList can add up to targetNumber?
I know I can write
if targetNumber = 12 then
if 1 is in theList and 2 is in theList and 9 is in theList
else if 1 is in theList and 3 is in theList and 8 is in the List ETC.ETC.ETC.,
I’m just hoping that there’s an easier routine that a better scripter than myself might know.
Thanks a bunch for any help
property target : 12
global lst, sum
set lst to {1, 2, 3, 5, 7, 9}
set sum to 0
if tr(1) then -- start with first list item
display dialog "yes"
else
display dialog "no"
end if
on tr(n)
if n > (count lst) then
if sum = target then return true
else
if tr(n + 1) then return true -- try without current item
set sum to sum + (item n of lst)
if tr(n + 1) then return true -- try *with* current item
set sum to sum - (item n of lst)
end if
return false
end tr
on tr(sum, target, lst)
if lst = {} then return sum = target
return tr(sum, target, rest of lst) or tr(sum + (item 1 of lst), target, rest of lst) -- try without current item, then with
end tr
set target to 12
set lst to {1, 2, 3, 5, 7, 9}
tr(0, target, lst)