Lists, numbers, and math

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

This works:

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

Hope that helps…

  • Dan

That’s EXACTLY what I was looking for. Perfect.
You just took away hours of one-handed, two fingered typing for me.
1,000 thank-you’s,
-G

Nice. FWIW, if you eliminate the clumsy globals:

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)

You’re very welcome Gassy. hhas, yes that is slicker. “rest of lst”? I never even heard of that. I’ll have to keep that in mind…

See: http://developer.apple.com/documentation/AppleScript/Conceptual/AppleScriptLangGuide/AppleScript.28.html

HTH