Last active
September 1, 2018 11:30
-
-
Save rayshih/764751169c2134abac5fbcf41312ba4b to your computer and use it in GitHub Desktop.
Practice N Queen problem in term level PureScript
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
module Main where | |
import Prelude | |
import Control.Monad.Eff (Eff) | |
import Control.Monad.Eff.Console (logShow, CONSOLE) | |
import Data.Ord (abs) | |
import Data.List (List(Nil), mapWithIndex, range, (:), filter, length, foldl) | |
import Data.Foldable (all) | |
import Data.Traversable (traverse) | |
import TryPureScript (render, withConsole, DOM) | |
checkVertical :: List Int -> Int -> Boolean | |
checkVertical arr n = all (_ /= n) arr | |
checkDiagonal :: List Int -> Int -> Boolean | |
checkDiagonal arr cc = all id $ mapWithIndex checkOne arr | |
where | |
checkOne r c = abs (r + 1 - 0) /= abs (c - cc) | |
-- check whether n can be prepend to the arr | |
check :: List Int -> Int -> Boolean | |
check arr n = checkDiagonal arr n && checkVertical arr n | |
-- place one by prepend | |
placeOne :: Int -> List Int -> List (List Int) | |
placeOne n arr = | |
range 0 (n - 1) | |
# filter (check arr) | |
# map (_ : arr) | |
nQueen :: Int -> List (List Int) | |
nQueen n = go Nil Nil | |
where | |
go acc arr | |
| length arr == n = arr : acc | |
| otherwise = foldl go acc $ placeOne n arr | |
main :: forall eff. Eff (dom :: DOM, console :: CONSOLE | eff) Unit | |
main = render =<< withConsole do | |
range 1 10 # | |
traverse (logShow <<< length <<< nQueen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment