fork(1) download
  1. ; the early bird catches the worm
  2.  
  3. (import (rnrs exceptions (6)))
  4. (import (rnrs sorting (6)))
  5.  
  6. (define (undigits ds . args)
  7. (let ((b (if (null? args) 10 (car args))))
  8. (let loop ((ds ds) (n 0))
  9. (if (null? ds) n
  10. (loop (cdr ds) (+ (* n b) (car ds)))))))
  11.  
  12. (define (permutations xs)
  13. (define (rev xs n ys)
  14. (if (zero? n) ys
  15. (rev (cdr xs) (- n 1) (cons (car xs) ys))))
  16. (let ((xs xs) (perms (list xs)))
  17. (define (perm n)
  18. (if (> n 1)
  19. (do ((j (- n 1) (- j 1)))
  20. ((zero? j) (perm (- n 1)))
  21. (perm (- n 1))
  22. (set! xs (rev xs n (list-tail xs n)))
  23. (set! perms (cons xs perms)))))
  24. (perm (length xs))
  25. perms))
  26.  
  27. (define-syntax try
  28. (syntax-rules (trying)
  29. ((try trying expr default)
  30. (call-with-current-continuation
  31. (lambda (return)
  32. (with-exception-handler
  33. (lambda (x) (return default))
  34. (lambda () expr)))))
  35. ((try) #f)
  36. ((try expr) (try trying expr #f))
  37. ((try expr0 expr1 ...)
  38. (let ((t (try trying expr0 #f)))
  39. (if t t (try expr1 ...))))))
  40.  
  41. (define (time? n)
  42. (and (< (quotient n 100) 24)
  43. (< (modulo n 100) 60)))
  44.  
  45. (define (earliest xs)
  46. (try (car
  47. (list-sort <
  48. (filter time?
  49. (map undigits
  50. (permutations xs)))))
  51. #f))
  52.  
  53. (display (earliest '(1 2 3 4))) (newline)
  54. (display (earliest '(6 7 8 9))) (newline)
Success #stdin #stdout 0.02s 44792KB
stdin
Standard input is empty
stdout
1234
#f