Five programming problems every Software Engineer should be able to solve in less than 1 hour
Geoff Canyon
gcanyon at gmail.com
Sun May 10 11:42:25 EDT 2015
I rewrote the function to take arbitrary arguments for the list of numbers
and the target value, and then took advantage of the fact that char 0 of
"+-" is empty:
function problem5 S,T
local tResults
local countLessOne
local tScheme
local tSum
split S using comma
put (item 2 of the extents of S) - 1 into countLessOne
repeat with i = 0 to 3^(countLessOne)
put empty into tSum
put format("%0" & countLessOne & "s", baseConvert(i, 10, 3)) into
tScheme
repeat with j = 1 to countLessOne
put S[j] & char (char j of tScheme) of "+-" after tSum
end repeat
put S[countLessOne + 1] after tSum
if value(tSum) is T
then put tSum & return after tResults
end repeat
return tResults
end problem5
On Sun, May 10, 2015 at 10:21 AM, Geoff Canyon <gcanyon at gmail.com> wrote:
>
> On Sun, May 10, 2015 at 5:38 AM, Mark Waddingham <mark at livecode.com>
> wrote:
>
>> ---- PROBLEM 5
>> ---- At first sight this one seems 'scary' but in actual fact the
>> ---- number of combinations is actually quite small (3^8) and you
>> ---- can get them by counting from 0 to 3^8 in ternery and padding
>> ---- the result to 8 digits. I then use 0 for no sign, 1 for + and
>> ---- 2 for -. Having 'value' makes checking the sums trivial.
>>
>
> I thought briefly about doing this but it didn't gel in my mind as quickly
> as the substitution method I used. I quite like how this turned out!
>
More information about the use-livecode
mailing list