; the early bird catches the worm (import (rnrs exceptions (6))) (import (rnrs sorting (6))) (define (undigits ds . args) (let ((b (if (null? args) 10 (car args)))) (let loop ((ds ds) (n 0)) (if (null? ds) n (loop (cdr ds) (+ (* n b) (car ds))))))) (define (permutations xs) (define (rev xs n ys) (if (zero? n) ys (rev (cdr xs) (- n 1) (cons (car xs) ys)))) (let ((xs xs) (perms (list xs))) (define (perm n) (if (> n 1) (do ((j (- n 1) (- j 1))) ((zero? j) (perm (- n 1))) (perm (- n 1)) (set! xs (rev xs n (list-tail xs n))) (set! perms (cons xs perms))))) (perm (length xs)) perms)) (define-syntax try (syntax-rules (trying) ((try trying expr default) (call-with-current-continuation (lambda (return) (with-exception-handler (lambda (x) (return default)) (lambda () expr))))) ((try) #f) ((try expr) (try trying expr #f)) ((try expr0 expr1 ...) (let ((t (try trying expr0 #f))) (if t t (try expr1 ...)))))) (define (time? n) (and (< (quotient n 100) 24) (< (modulo n 100) 60))) (define (earliest xs) (try (car (list-sort < (filter time? (map undigits (permutations xs))))) #f)) (display (earliest '(1 2 3 4))) (newline) (display (earliest '(6 7 8 9))) (newline)