• ### Calculating the digit sum of an integer / using while-loops in [expr]

I am sitting with a little patch here... I want to calculate the digit sum of an integer.
What I have so far works with any integer up to and including 99. But the trouble starts at n >= 100.
See the patch attached: DigitSum.pd

I got this working in Python, for any integers:

def digSum(n):

out = 0
while (n != 0):
out = out + int(n % 10)
n = int(n/10)

return out

for x in range(1,200):
n = x
print(n, ":", digSum(n))

But [expr] seems to not do while-loops, unless I am mistaken?
I have tried sloppy workarounds, chaining up multiple [expr} objects, but it's error-prone, ugly, and convoluted.
The end goal is to be able store the digit sums of a given range of integers in an array; Like you can see in the right-hand section of the DigitSum.pd patch.

Anything I am missing here?

• Posts 8 | Views 580
• true, don't try to use [expr] for everything.
The purpose of [expr] is to evaluate mainly mathematical expressions. yes it has an 'if' function but the main purpose is simple expressions.

so, put your loop/running sum outside of the [expr]s. you can use [until] to generate a loop

• @seb-harmonik.ar Perfect example of what I call "initialize -- run -- finalize," organized by the [t] at the top. I'd call it "textbook" except... did anybody write a textbook about algorithms in patchers?

hjh

• @seb-harmonik.ar
Wow, thanks a lot! A very interesting patch, going through this one step by step has taught me a lot.
And very true what you said about the purpose and use of [expr]. I see now that I used to look at the object as something completely different than it's actual purpose.

• i dont see the need for that "until loop", if 1000 is not present it would just accumulate another 0.

okay, it might get quite long if you do that for 8 or 10 digits. but a pure arithmetic, one-object solution is possible

(int(\$i1-(int(\$i1/10)*10))/1) + (int(\$i1-(int(\$i1/100)*100))/10) + (int(\$i1-(int(\$i1/1000)*1000))/100) + (int(\$i1-(int(\$i1/10000)*10000))/1000) + (int(\$i1-(int(\$i1/100000)*100000))/10000) + (int(\$i1-(int(\$i1/1000000)*1000000))/100000) + (int(\$i1-(int(\$i1/10000000)*10000000))/1000000) + (int(\$i1-(int(\$i1/100000000)*100000000))/10000000)

feel free to make it a bit shorter using modulo operator - i´d prefer it like so.

• oh, you can also make it shorter by writing 10^5

• @Obineg said:

i dont see the need for that "until loop"

While / until is an incredibly valuable concept in all types of programming, including patching, and this problem is an ideal case for it.

hjh

Posts 8 | Views 580
Internal error.

Oops! Looks like something went wrong!