Skip to content

Instantly share code, notes, and snippets.

@rayshih
Last active September 1, 2018 11:30
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 rayshih/764751169c2134abac5fbcf41312ba4b to your computer and use it in GitHub Desktop.
Save rayshih/764751169c2134abac5fbcf41312ba4b to your computer and use it in GitHub Desktop.
Practice N Queen problem in term level PureScript
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