Skip to content

Instantly share code, notes, and snippets.

@otherjoel
Created June 16, 2020 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otherjoel/866959c0b627f55539b4d57280f4769f to your computer and use it in GitHub Desktop.
Save otherjoel/866959c0b627f55539b4d57280f4769f to your computer and use it in GitHub Desktop.
Count the possible sandwiches in a loaf of bread (Racket)
#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