Counting Digits
January 7, 2020
Here’s our solution:
(define (f lo hi) (define (is258 d) (or (= d 2) (= d 5) (= d 8))) (define (cnt n) (length (filter is258 (digits n)))) (do ((n lo (+ n 1)) (c 0 (+ c (cnt n)))) ((< hi n) c))) > (f 295 395) 9 > (time (f 11 100000)) (time (f 11 ...)) 2 collections 0.018759638s elapsed cpu time, including 0.000229760s collecting 0.018892309s elapsed real time, including 0.000238270s collecting 9539376 bytes allocated, including 16834208 bytes reclaimed 149997
You can run the program at https://ideone.com/FA3ADI.
Happy new year & I hope everyone enjoyed the holiday break.
I thought that should be a more direct way of counting the digits than enumerating the entire range. For simplicity, dcount counts all the digits in range(n) – ie. not including n itself:
That needs some modification for digit ‘0’ (an exercise for the reader)- also the while condition can be ‘n > m’
This is better (and the ‘0’ count is correct if we assume numbers are zero padded on the left to the same length):
Or wrap the whole thing up in a list comprehension:
Klong version
Klong results:
{+/{[n];n::x;+/{#($n)?$x}'”258″}’x+!1+y-x}(295;305)
9
Here’s a solution in Python, based on the digit counting algorithm from here.
Output: