Sunday, October 27, 2013

Problem 57 - Racket

After struggling with trying to use C# to solve Problem 57, I realized that Racket was perfect for it. Racket is a language that I am very familiar with, it is fairly easy to program in (being a dialect of Lisp), and it has native support for arbitrary precision rational numbers...making it perfect for solving Problem 57, which involves keeping track of rational numbers with very large numerators and denominators. After my failed C# attempt had a 50 line Rational struct and was going to get larger and more unwieldy, I finally came to my senses and wrote the below script in Racket, which runs in about half a second.
#lang racket

(define (digits x)
  (if (< x 10) 1 (add1 (digits (quotient x 10)))))

(define (nth-conv n)
  (define (help m)
    (if (= m 1) 1/2 (/ 1 (+ 2 (help (sub1 m))))))
  (add1 (help n)))

(define (topheavy r)
  (if (> (digits (numerator r)) (digits (denominator r))) 1 0))

(foldr + 0 (map (λ (x) (topheavy (nth-conv x))) (build-list 1000 add1)))

No comments:

Post a Comment