Scheme - retrieve occurrences of a digit in a number -



Scheme - retrieve occurrences of a digit in a number -

i'm working through bert scheme exercises , having tough time one:

example : (n-occurences 544555 5) => 4

any ideas how have count going?

i thinking like:

(define (occurences d n) (if (equal? (remainder d 10) n) (add1 (occurences (quotient d 10) n)) (occurences (quotient d 10) n) ))

so in illustration such 1223 2 would:

check if 3 2 say no, , move on , phone call 1 time again 122 2 check if 2 2 say yes, , add together 1 phone call 12 2 (count 1) check if 2 2. say yes, , add together 1 phone call 1 2 (count 2) check if 1 2. say no , done.

you missing base of operations case of recursion; need stop if d 0. , mixed n , d few times:

(define (occurences d n) (if (= 0 d) (if (= 0 n) 1 0) ; base of operations case (if (= (remainder d 10) n) (add1 (occurences (quotient d 10) n)) (occurences (quotient d 10) n))))

testing:

> (occurences 544555 5) 4

the parameters (d , n) evolve follows:

d=544555 n=5 d=54455 n=5 d=5445 n=5 d=544 n=5 d=54 n=5 d=5 n=5 d=0 n=5

scheme

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -