#Factor with load-all, 175 bytes
Factor with load-all, 175 bytes
Well, this is not very short. The special handling of unary minus is really annoying; I guess I could do it better and I will, maybe.
[ dup [ 10 >base length ] [ [ 10 >base >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ] bi + + ] Using this substitution regex:
s/(-?[\d]+)\s*->\s*(-?[\d]+)/{ $2 } [ $1 calculate-ild ] unit-test/g We can turn the OP's test cases into a Factor test suite.
USING: arrays kernel math math.parser sequences ; IN: sum-ild : sum-digits ( n -- x ) [ number>string >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ; : calculate-ild ( n -- x ) dup [ number>string length ] [ sum-digits ] bi + + ; USING: tools.test sum-ild ; IN: sum-ild.tests { 87931 } [ 87901 calculate-ild ] unit-test { 132 } [ 123 calculate-ild ] unit-test { 119 } [ 99 calculate-ild ] unit-test { 11 } [ 5 calculate-ild ] unit-test { 3 } [ 1 calculate-ild ] unit-test { 1 } [ 0 calculate-ild ] unit-test { -4 } [ -3 calculate-ild ] unit-test { -115 } [ -123 calculate-ild ] unit-test { -905 } [ -900 calculate-ild ] unit-test { -87886 } [ -87901 calculate-ild ] unit-test