Wednesday, August 14, 2013

Problem 26 - Racket

So, I recently got Racket/Scheme back as a potential language after redoing the problem I first did in Racket in Postscript. I originally did my first 50 or so euler solutions in Racket, so I am pretty familiar with it - however, this time I was either tired or using this language that I haven't used for a while brought back old bad habits, so my solution, while working, is, I think, pretty sloppy (or at least the way I wrote it was pretty sloppy...constantly tweaking things in a mildly haphazard fashion until I got a correct solution). Anyway, this served as a brief interlude as I have begun working on Problem 27 and needed a break...I am writing that solution in Befunge, which is just a little crazy.
#lang racket

(define (index-of l x)
  (for/or ([y l] [i (in-naturals)] #:when (equal? x y)) i))

(define (biggest-cycle x)
  (define (helper prev lst)
    (let ([n (modulo (* 10 prev) x)])
      (if (zero? n) 0
        (if (and (member (* 10 prev) lst) (< x (* 10 prev))) 
            (- (length lst) (index-of lst (* 10 prev))) 
            (helper n (append lst (cons (* 10 prev) '())))))))
  (helper 1 '()))

(define (euler26)
  (define (f x max maxn)
    (let ([k (biggest-cycle x)])
      (if (= x 1000) maxn
          (if (> k max) (f (add1 x) k x) (f (add1 x) max maxn)))))
  (f 1 0 0))
        
(euler26)

No comments:

Post a Comment