[racket] do loops in racket, also srfi/25 query

From: Tom McNulty (tom.mcnulty at gmail.com)
Date: Sun Mar 25 02:26:54 EDT 2012

The format of prob11's data is already quite close to what the reader expects for a vector, so you can read it directly by including #( ...

(define tbl
  #(08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
	<snip> ...
    01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48))

A convenience function to read the table is then:

(define (get i j)
  (vector-ref tbl (+ (* i 20) j)))

Here is my across function, I use a for/fold loop.  The vertical and diagonal cases are similar. 

(define (across)
  (for*/fold ([mx 0])
             ([i (in-range 0 20)]
              [j (in-range 0 17)])
             (max mx (* (get i j)
                        (get i (+ j 1))
                        (get i (+ j 2))
                        (get i (+ j 3))))))

Does that help? 


- Tom

On 2012-03-24, at 11:01 PM, Joe Gilray wrote:

> I was playing around with ProjectEuler #11 and found a lisp solution and adapted it to Racket.  Part of the solution had code like the following to find products of values in a 20x20 vector.
> 
> (define (prod-of-vec-lines-of-length-4 v ix iy dx dy)
>   (do ([p 1 (* p (if (in-vector? x y 20 20) (vector-ref v (+ (* 20 y) x)) 0))] 
>        [x ix (+ x dx)] 
>        [y iy (+ y dy)] 
>        [c 0 (add1 c)]) 
>     ((= c 4) p)))
> 
> I realize I've hard-coded this in a very ugly fashion to 20x20 vectors. 
> 
> My questions are:
> 
> 1) Is there a more Racket-idiomatic way to write the "do" loop above?
> 2) If I wanted to use srfi/25 to do this in a nicer fashion, how would I read in the array? - I liked being able to read in the vector with simply (read in) - is there a simply , one-line way to convert a vector to an array (make-array (shape 0 20 0 20) vec) puts the entire 400 element vector into the first element of the array!
> 
> Thanks,
> -joe
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 841 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://lists.racket-lang.org/users/archive/attachments/20120325/adfa5ff2/attachment.sig>

Posted on the users mailing list.