Sum of integers in a string

Q&A's, tips, howto's
Post Reply
cameyo
Posts: 115
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy

Sum of integers in a string

Post by 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
Posts: 61
Joined: Sat Nov 09, 2013 8:49 pm

Re: Sum of integers in a string

Post by fdb »

Hi cameo,

my first attempt would be:

Code: Select all

(define (parse-str str)
  (apply + (map int (clean empty? (parse str {[^0-9]} 0)))))
if it needs to be faster I would do:

Code: Select all

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

cameyo
Posts: 115
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy

Re: Sum of integers in a string

Post by cameyo »

Hi fdb,
thanks for your functions.
Only a problem: numbers with leading 0 will convert in octal base.

Code: Select all

Es. (parse-str "o123p010iru5") -> 136 (the correct value is 138)
My function:

Code: Select all

(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
Posts: 149
Joined: Fri Oct 28, 2005 5:33 pm
Location: France

Re: Sum of integers in a string

Post by newBert »

In this case we could also do:

Code: Select all

> (apply + (map (fn (x) (int (if (starts-with x "0") (rest x) x))) (find-all {[0-9]+} "o123p010iru5")))
138
BertrandnewLISP v.10.7.6 64-bit on Linux (Peppermint 9)

fdb
Posts: 61
Joined: Sat Nov 09, 2013 8:49 pm

Re: Sum of integers in a string

Post by fdb »

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: Select all

> (apply + (map int (find-all {[1-9][0-9]*} "o123p010iru5")))
138
>

fdb
Posts: 61
Joined: Sat Nov 09, 2013 8:49 pm

Re: Sum of integers in a string

Post by fdb »

Or replacing the map with a function for apply, so only traversing the string two times

Code: Select all

> (apply (fn(x y) (+ (int x) (int y))) (find-all {[1-9]\d*} "o123p0010iru5") 2) 
138

cameyo
Posts: 115
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy

Re: Sum of integers in a string

Post by cameyo »

thank you. I learned new things.

newBert
Posts: 149
Joined: Fri Oct 28, 2005 5:33 pm
Location: France

Re: Sum of integers in a string

Post by newBert »

cameyo wrote:
Fri Jul 03, 2020 10:26 am
thank you. I learned new things.
You're welcome! I learned new things too... :)
BertrandnewLISP v.10.7.6 64-bit on Linux (Peppermint 9)

Post Reply