Created
June 16, 2020 21:44
-
-
Save otherjoel/866959c0b627f55539b4d57280f4769f to your computer and use it in GitHub Desktop.
Count the possible sandwiches in a loaf of bread (Racket)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(require threading) | |
(define (slice-pairs slice-count) | |
(combinations (range slice-count) 2)) | |
;; Any two non-adjacent slices form a sandwich | |
(define (sandwich-pair? lst) | |
(and (list? lst) | |
(equal? 2 (length lst)) | |
(> (abs (apply - lst)) 1))) | |
(define (possible-sandwiches slice-count) | |
(~>> (slice-pairs slice-count) | |
(map sandwich-pair?) | |
(filter identity) | |
length)) | |
;; Or...the math way... | |
(define (possible-sandwiches-using-math slice-count) | |
(~> (- slice-count 2) | |
(* (- slice-count 1)) | |
(/ 2))) | |
(module+ test | |
(require rackunit) | |
(for ([func (in-list (list possible-sandwiches | |
possible-sandwiches-using-math))]) | |
(check-equal? (func 4) 3) | |
(check-equal? (func 8) 21) | |
(check-equal? (func 20) 171))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment