[racket] a small programming exercise
Code is below. There's something stupidly verbose about the way I extract
the first digit, so suggestions are welcome.
(define (count-firsts d)
(let ((c (make-vector 9 0)))
(let loop ((d d))
(if (null? d)
(let* ((cl (vector->list c))
(sum (exact->inexact (apply + cl))))
(map list
(build-list 9 add1)
(map (lambda (x) (/ x sum)) cl)))
(let* ((first (string->number
(list->string
(list
(car (string->list
(number->string (car d))))))))
(ind (sub1 first)))
(vector-set! c ind (add1 (vector-ref c ind)))
(loop (cdr d)))))))
On Thu, Oct 14, 2010 at 12:10 AM, Shriram Krishnamurthi <sk at cs.brown.edu>wrote:
> Given: A list of numbers. Assume integers (though it isn't necessary
> for the underlying issue).
>
> Task: To determine how often the first digit is 1, the first digit is
> 2, ..., the first digit is 9, and present as a table. You may exploit
> DrRacket's pretty-printer, e.g., by using a list of lists:
>
> '((#\1 22.51539138082674)
> (#\2 16.44678979771328)
> (#\3 15.567282321899736)
> (#\4 12.401055408970976)
> (#\5 9.058927000879507)
> (#\6 7.651715039577836)
> (#\7 6.420404573438875)
> (#\8 5.804749340369393)
> (#\9 4.133685136323659))
>
> I leave the precise format of the output unstated so you're free to
> choose a clever representation; your answer should be at least as
> visually clear as the above.
>
> You should not mutate the original list, since it may be necessary for
> other computations.
>
> Smallest/tightest/cleanest/best?
>
> Shriram
>
> PS: Of course, this is to explore Benford's Law:
>
> http://en.wikipedia.org/wiki/Benford's_law<http://en.wikipedia.org/wiki/Benford%27s_law>
>
> which is the subject of my lecture tomorrow. The above
> distribution is from the size of the littoral zone (in acres) of
> the lakes of Minnesota.
>
> PPS: If you really want to you can assume the data are actually in a
> CSV file (as mine are -- thanks, Neil!), in case you can come up
> with something even cleverer.
> _________________________________________________
> For list-related administrative tasks:
> http://lists.racket-lang.org/listinfo/users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20101014/10d04ad2/attachment.html>