p085.scm 854 B

123456789101112131415161718192021222324252627
  1. ;; Counting rectangles
  2. ;; There clearly seems to be an elegant algorithm for this problem...
  3. ;; Turning this into a 1-d problem...
  4. ;; Given block-size: we have: row-size - size perumations...
  5. ;; Then for the 2-d version, I think we just multiply.... since for each block config for 1-d, we have the number of permuations allowed in the the other direction..
  6. (define-module (solved p085))
  7. (define (rectangles-in-area n m)
  8. (* (/ (* n (+ n 1)) 2)
  9. (/ (* m (+ m 1)) 2)))
  10. (define (grid-w/~n-rectangles n)
  11. (let lp ([i 1] [j 1] [best '(0 0 0)])
  12. (let ([curr-count (rectangles-in-area i j)])
  13. (cond
  14. [(and (> curr-count n) (= 1 j)) best]
  15. [(> j i) (lp (1+ i) 1 best)]
  16. [(> curr-count n) (lp (1+ i) 1 best)]
  17. [else
  18. (lp i (1+ j)
  19. (if (< (- n curr-count)
  20. (- n (car best)))
  21. (list curr-count i j)
  22. best))]))))