Sum of integers in a string

Started by cameyo, June 30, 2020, 08:37:02 AM

Previous topic - Next topic

cameyo

A string consist of digits and non-digit characters. The digits contains a series of positive integers. For instance, the string "abc22zit62de0f" contains the integers 22, 62 and 0.

Write a function to calculate the sum of the integers inside a string (es. 22 + 62 + 0 = 84)

fdb

#1
Hi cameo,



my first attempt would be:
(define (parse-str str)
  (apply + (map int (clean empty? (parse str {[^0-9]} 0)))))


if it needs to be faster I would do:

(define (parse-str str)
(let (total 0)
(dolist (s (parse str {[^0-9]} 0))
(unless (empty? s)
(inc total (int s))))
total))

cameyo

#2
Hi fdb,

thanks for your functions.

Only a problem: numbers with leading 0 will convert in octal base.
Es. (parse-str "o123p010iru5") -> 136 (the correct value is 138)
My function:
(define (sum-str str)
  (local (numeri expr)
    (setq numeri '())
    (setq expr {[0-9]+})
    (replace expr str (push $0 numeri -1) 0)
    (apply + (map (fn (x) (int x 0 10)) numeri))
  ))
(sum-str "o123p010iru5")
;-> 138

best regards,

cameyo

newBert

#3
In this case we could also do:
> (apply + (map (fn (x) (int (if (starts-with x "0") (rest x) x))) (find-all {[0-9]+} "o123p010iru5")))
138
<r><I>>Bertrand<e></e></I> − <COLOR color=\"#808080\">><B>newLISP<e></e></B> v.10.7.6 64-bit <B>>on Linux<e></e></B> (<I>>Linux Mint 20.1<e></e></I>)<e></e></COLOR></r>

fdb

#4
Nice, I didn't know starts-with and didn't know I could use a regex in find-all, but then we could also simplify your code:[code]
> (apply + (map int (find-all {[1-9][0-9]*} "o123p010iru5")))
138
>

fdb

#5
Or replacing the map with a function for apply, so only traversing the string two times  
> (apply (fn(x y) (+ (int x) (int y))) (find-all {[1-9]d*} "o123p0010iru5") 2)
138

cameyo

#6
thank you. I learned new things.

newBert

#7
Quote from: cameyo post_id=24891 time=1593772007 user_id=732
thank you. I learned new things.

You're welcome! I learned new things too... :)
<r><I>>Bertrand<e></e></I> − <COLOR color=\"#808080\">><B>newLISP<e></e></B> v.10.7.6 64-bit <B>>on Linux<e></e></B> (<I>>Linux Mint 20.1<e></e></I>)<e></e></COLOR></r>