Sunday, November 27, 2022

#1 2003-04-29 12:37:00 pm

Trash Man
Sanitation Department
Registered: 2005-10-20
Posts: 5336

Sum Integers by Hand

This handler will sum what AppleScript doesn't.
To make it work, you must provide a list of strings (numbers), without any limitation of its number of digits.

OS version: OS X


sumIntegersByHand({"123", "98765432109876543210", "98765432109876543210"})

to sumIntegersByHand(string_list)
   --> reverse items to build columns
   repeat with i from 1 to string_list's length
       set string_list's item i to (reverse of (string_list's item i)'s items as text)
   end repeat
   set sum_result to {}
   set current_digit to 1
   set the_rest to 0
           --> get column of current digit
           set digit_list to {}
           repeat with i in string_list
                   set end of digit_list to (i's item current_digit as integer)
               end try
           end repeat
           if digit_list = {} then exit repeat
           --> sum column
           set partial_result to 0
           repeat with i in digit_list
               set partial_result to partial_result + i
           end repeat
           --> sum rest, if exists
           set partial_result to partial_result + the_rest
           set beginning of sum_result to partial_result mod 10
           set the_rest to partial_result div 10
           set current_digit to current_digit + 1
       on error msg
           exit repeat
       end try
   end repeat
   if the_rest is not 0 then set beginning of sum_result to the_rest
   return sum_result as text
end sumIntegersByHand

One mans trash is another mans treasure



Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)