Created
October 11, 2024 16:56
-
-
Save harismh/d5bd8d212ee7fd148a9750390775d088 to your computer and use it in GitHub Desktop.
Tic-Tac-Toe Magic Squares
This file contains hidden or 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
(ns tic-tac-toe-magic-squares | |
(:require [clojure.math.combinatorics :refer [combinations]])) | |
(defn magic-square-n [magic-square] | |
(int (Math/sqrt (count magic-square)))) | |
(defn range-n2 [n] | |
(range 1 (+ 1 (* n n)))) | |
(defn magic-constant [n] | |
(/ (reduce + (range-n2 n)) n)) | |
(defn square-combinations [n] | |
(combinations (range-n2 n) n)) | |
(defn winning-combinations [n] | |
(->> | |
(filter #(= (first %) (magic-constant n)) | |
(map | |
(fn [combination] | |
[(reduce + combination) combination]) | |
(square-combinations n))) | |
(map second))) | |
(defn filterf [pred coll] | |
(first (filter pred coll))) | |
(defn find-index [x coll] | |
(filterf (complement nil?) | |
(for [i (range (count coll))] | |
(when (= (get coll i) x) i)))) | |
(defn all=? [coll] | |
(and (not= (count coll) 0) | |
(every? #(= % (first coll)) coll))) | |
(defn board-combination-winner | |
[combination magic-square board] | |
(let [xs (map #(find-index % magic-square) combination) | |
pos (map #(get board %) xs)] | |
(when (all=? pos) | |
(first pos)))) | |
(defn winner [magic-square board] | |
(filterf (complement nil?) | |
(for [combination (winning-combinations | |
(magic-square-n magic-square))] | |
(board-combination-winner | |
combination magic-square board)))) | |
(comment | |
(winner | |
[2 7 8 | |
9 5 1 | |
4 3 6] | |
[:x nil :x | |
:o :x nil | |
:o :o :x]) ; => :x | |
(winner | |
[ 1 15 14 4 | |
10 11 8 5 | |
7 6 9 12 | |
16 2 3 13] | |
[:x :o :x :o | |
:x :o :o :x | |
:o :o :x :x | |
:o nil nil nil]) ; => :o | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment