[racket] spirit of Racket?
This is a great situation to use Racket's advanced list
comprehensions. There is no need to use set!. You can keep track of
the maximum as you loop. Here is my solution.
; Problem 4
; Find the largest palindrome made from the product of two 3-digit numbers.
; 3-digit numbers are the numbers 100-999
(define (pe-004)
(for*/fold ([greatest 0])
([first (in-range 101 1000)]
[second (in-range 101 1000)]
#:when (palindrome? (* first second)))
(max greatest (* first second))))
Justin
On Sun, Mar 11, 2012 at 4:12 PM, Joe Gilray <jgilray at gmail.com> wrote:
> Hi, I'm redoing the ProjectEuler problems to learn Racket (great fun!).
> Below are three solutions to PE#4. Which is most in the spirit of Racket?
> Of course, I'd love to see solutions that are more idiomatic too. Is there
> a better way that doesn't use "for" at all?
>
> Thanks!
> -Joe
>
> ; function that turns a positive integer into a list of digits (in reverse
> order)
> ; invoke as (listize 234511) or (set-count (list->set (listize 112342)))
> (define (listize num)
> (if (= num 0)
> '()
> (cons (remainder num 10) (listize (quotient num 10)))))
>
> ; function that returns #t if the passed number is palindromic
> ; invoke as (palindromic? n)
> (define (palindromic? n)
> (if (equal? (listize n) (reverse (listize n))) #t #f))
> )
>
> ; ProjectEuler problem #4
> (define (euler4a)
> (let ([max 100000])
> (for ([i (build-list 899 (lambda (x) (+ 100 x)))])
> (for ([j (build-list (- 999 i) (lambda (y) (+ i y)))])
> (let ([prod (* i j)])
> (when (palindromic? prod)
> (begin
> (when (> prod max) (set! max prod))
> (printf "~a * ~a = ~a~n" i j prod))))))
> (printf "Max palindromic product is ~a~n" max)))
>
> ; ProjectEuler problem #4 using for*
> (define (euler4b)
> (let ([max 100000])
> (for* ([i (build-list 899 (lambda (x) (+ 100 x)))]
> [j (build-list 899 (lambda (y) (+ 100 y)))]
> #:when (and (>= j i) (palindromic? (* i j))))
> (let ([prod (* i j)])
> (when (> prod max) (set! max prod))
> (printf "~a * ~a = ~a~n" i j prod)))
> (printf "Max palindromic product is ~a~n" max)))
>
> ; ProjectEuler problem #4 - a mix of 4a and 4b
> (define (euler4c)
> (let ([max 100000])
> (for* ([i (build-list 899 (lambda (x) (+ 100 x)))]
> [j (build-list (- 999 i) (lambda (y) (+ i y)))]
> #:when (palindromic? (* i j)))
> (let ([prod (* i j)])
> (when (> prod max) (set! max prod))
> (printf "~a * ~a = ~a~n" i j prod)))
> (printf "Max palindromic product is ~a~n" max)))
>
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users
>