Hi, On ProjectEuler #14 I tried to use hashes for the first time and although I got it to work, I feel like my use of hashes needs help:
(define (euler14) (define ht (make-hash)) (hash-set! ht 1 1) (define start-longest-chain 1) (define longest-chain 1) (for ([i (in-range 2 1000000)]) (unless (hash-has-key? ht i) (let loop ([count 0] [cur i] [lst '()]) (define col (collatz cur)) (if (hash-has-key? ht col) (let ([colval (hash-ref ht col)]) (when (< longest-chain (+ 1 colval (abs count))) (begin (set! longest-chain (+ 1 colval (abs count))) (set! start-longest-chain i))) (for ([ps (cons (list i 1) lst)]) (hash-set! ht (car ps) (+ (abs count) (cadr ps) colval)))) (loop (sub1 count) col (cons (list col count) lst)))))) (values start-longest-chain longest-chain)) Specifically, 1) Why do I have to use two lines to set the (1 . 1) base case? I really tried to use the associations argument but got: > (define ggg (make-hash (list '(1 4)))) > (hash-ref ggg 1) '(4) > (hash-set! ggg 1 4) > (hash-ref ggg 1) 4 I can't seem to make the optional argument to make-hash work to give me simply a number. 2) My use of hash-has-key? feels clunky, Could I better use hash-ref? especially here: (if (hash-has-key? ht col) (let ([colval (hash-ref ht col)]) ... Thanks for any advice. -Joe
____________________ Racket Users list: http://lists.racket-lang.org/users