Skip to content

Instantly share code, notes, and snippets.

@greymd greymd/inverse-fizzbuzz.md
Last active Sep 24, 2017

Embed
What would you like to do?
Inverse Fizzbuzz with Egison

inverse-fizzbuzz.egi

(define $main
  1#(do {
      (answer "fizz")               ; => {[3 3]}
      (answer "buzz")               ; => {[5 5]}
      (answer "fizz" "fizz" "buzz") ; => {[6 10]}
      (answer "fizz" "buzz")        ; => {[9 10]}
      (answer "buzz" "fizz")        ; => {[5 6]}
      (answer "fizz" "buzz" "fizz") ; => {[3 6]}
      (answer "fizz" "fizz")        ; => {[6 9]}
      (answer "fizz" "fizzbuzz" "fizz" "buzz" "fizz" "fizz"
                       "buzz" "fizz" "fizzbuzz" "fizz" "buzz" "fizz"
                       "fizz" "buzz" "fizz" "fizzbuzz" "fizz" "buzz") ; => {[12 50]}
      (answer "buzz" "fizz" "buzz") ; => {} (no answer)
      }))

(define $answer
  (cambda $arr
          (do {
            (print (S.append (S.intercalate " " {@arr " -> "})
                             (show (take 1
                                         (sort/fn
                                           2#(compare (2#(- %2 %1) %1) (2#(- %2 %1) %2))
                                           (map 1#[(2#%1 (car %1)) (2#%1 (rac %1))]
                                                (inv-fizzbuzz arr)))))))
               })))

(define $inv-fizzbuzz
  (lambda $pat
    (let {[$n (length pat)]
          [$arr (generate-array (nth $ pat) [1 (length pat)])]}
      (match-all (take (+ n 7) fizzbuzz) (list [integer string])
        [<join _
          (loop $idx [1 n]
               <cons (& [_ ,arr_idx] $mat_idx) ...> _) >
         (map 1#mat_%1 (between 1 n))]))))

(define $fizzbuzz
  (filter 2#(not (eq? <Nil> %2)) fizzbuzz-all))

(define $fizzbuzz-all
  (map
    3#(match [%1 %2 %3] something {
        [[$i ,0 ,0] [i "fizzbuzz"]]
        [[$i ,0 _]  [i "fizz"]]
        [[$i _ ,0]  [i "buzz"]]
        [[$i _ _]   [i <Nil>]]})
    (map 1#[%1 (modulo %1 3) (modulo %1 5)] nats)))
$ egison inverse-fizzbuzz.egi
fizz  -> {[3 3]}
buzz  -> {[5 5]}
fizz fizz buzz  -> {[6 10]}
fizz buzz  -> {[9 10]}
buzz fizz  -> {[5 6]}
fizz buzz fizz  -> {[3 6]}
fizz fizz  -> {[6 9]}
fizz fizzbuzz fizz buzz fizz fizz buzz fizz fizzbuzz fizz buzz fizz fizz buzz fizz fizzbuzz fizz buzz  -> {[12 50]}
buzz fizz buzz  -> {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.