Skip to content

Instantly share code, notes, and snippets.

@jamiepratt
Last active June 5, 2022 23:15
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 jamiepratt/24d03edf6ef409e5d438108486d0edab to your computer and use it in GitHub Desktop.
Save jamiepratt/24d03edf6ef409e5d438108486d0edab to your computer and use it in GitHub Desktop.
(ns one-to-nine.core
(:require [clojure.math.combinatorics :as combo]))
(defn all-possible-boards
"What are all the possible combinations of the set of numbers from 1 to x."
[x]
(combo/permutations (range 1 (inc x))))
(defn horiz-vertical-coords
"Index for array for the rows and columns of a board with width * height squares"
[width height]
(let [rows (for [row (range 0 height)] (range (* row width) (* (inc row) width)))
columns (for [col (range 0 width)] (range col (* width height) width))]
(concat rows columns)))
(defn result-from-row-or-column[operations values-of-row-or-column]
(loop [acc (first values-of-row-or-column)
[value & next-values-to-operate-on] (rest values-of-row-or-column)
[op & next-operations] operations]
(if (seq next-values-to-operate-on)
(recur (op acc value) next-values-to-operate-on next-operations)
(op acc value))))
(defn results-from-board
[operations width height board]
(let [values-of-rows-and-columns (map #(map (partial nth board) %) (horiz-vertical-coords width height))]
(map (partial result-from-row-or-column operations) values-of-rows-and-columns)))
(defn board-from-results
"For boards width * height what are the possible combinations so that the results of operations
on rows and columns are `results`."
[operations width height results]
(let [boards (all-possible-boards (* width height))]
(filter #(= (results-from-board operations width height %) results) boards)))
(defn -main[ & args]
(println(board-from-results [* -] 3 3 '(-4 32 23 -1 6 9))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment