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:<div><br></div><div>(define (euler14)</div><div> (define ht (make-hash))</div><div> (hash-set! ht 1 1)</div>
<div> (define start-longest-chain 1)</div><div> (define longest-chain 1)</div><div> (for ([i (in-range 2 1000000)])</div><div> (unless (hash-has-key? ht i)</div><div> (let loop ([count 0] [cur i] [lst '()])</div>
<div> (define col (collatz cur))</div><div> (if (hash-has-key? ht col)</div><div> (let ([colval (hash-ref ht col)])</div><div> (when (< longest-chain (+ 1 colval (abs count))) </div>
<div> (begin</div><div> (set! longest-chain (+ 1 colval (abs count)))</div><div> (set! start-longest-chain i)))</div><div> (for ([ps (cons (list i 1) lst)]) (hash-set! ht (car ps) (+ (abs count) (cadr ps) colval))))</div>
<div> (loop (sub1 count) col (cons (list col count) lst)))))) (values start-longest-chain longest-chain))</div><div><br></div><div>Specifically, </div><div><br></div><div>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:</div>
<div><br></div><div>> (define ggg (make-hash (list '(1 4))))</div><div>> (hash-ref ggg 1)</div><div>'(4)</div><div><div>> (hash-set! ggg 1 4)</div><div>> (hash-ref ggg 1)</div><div>4</div></div><div><br>
</div><div>I can't seem to make the optional argument to make-hash work to give me simply a number.</div><div><br></div><div>2) My use of hash-has-key? feels clunky, Could I better use hash-ref? especially here:</div>
<div><br></div><div><div> (if (hash-has-key? ht col)</div><div> (let ([colval (hash-ref ht col)]) ...</div></div><div><br></div><div>Thanks for any advice.</div><div>-Joe</div>