Skip to content

Instantly share code, notes, and snippets.

@jjst
Created June 22, 2018 15:08
Show Gist options
  • Save jjst/66c07ed4d16001cd3be4ad6120cfd2b9 to your computer and use it in GitHub Desktop.
Save jjst/66c07ed4d16001cd3be4ad6120cfd2b9 to your computer and use it in GitHub Desktop.
module Main exposing (main)
import Html exposing (Html)
-- MODEL
type alias Model =
List Bool
x = True
o = False
state : Model
state =
[ [ o, x, o, x, o ]
, [ o, x, x, x, x ]
, [ x, x, o, x, x ]
, [ x, x, x, x, x ]
, [ x, x, x, x, x ]
]
|> List.concatMap identity
moves =
[ ( 3, 2 )
, ( 2, 4 )
, ( 3, 3 )
, ( 0, 3 )
, ( 1, 2 )
, ( 3, 1 )
, ( 1, 4 )
, ( 4, 0 )
, ( 1, 4 )
, ( 0, 1 )
, ( 0, 1 )
, ( 0, 2 )
, ( 0, 2 )
, ( 3, 1 )
, ( 0, 4 )
, ( 2, 2 )
, ( 1, 3 )
, ( 3, 1 )
, ( 2, 2 )
, ( 1, 1 )
, ( 0, 0 )
, ( 4, 3 )
, ( 4, 4 )
, ( 2, 3 )
, ( 4, 3 )
]
lightsOnCount : Model -> Int
lightsOnCount =
List.filter identity >> List.length
-- UPDATE
type alias Msg =
( Int, Int )
update : Msg -> Model -> Model
update msg model =
let
validNeighbors =
neighbors msg |> List.map index
in
List.indexedMap
(\index currentState ->
if List.member index validNeighbors then
not currentState
else
currentState
)
model
applyMoves : List Msg -> Model -> Model
applyMoves msgs model =
case msgs of
msg :: msgs ->
applyMoves msgs (update msg model)
[] ->
model
index : ( Int, Int ) -> Int
index ( x, y ) =
x * 5 + y
neighbors : ( Int, Int ) -> List ( Int, Int )
neighbors ( x, y ) =
let
allNeighbors =
[ ( x, y ), ( x - 1, y ), ( x + 1, y ), ( x, y - 1 ), ( x, y + 1 ) ]
validNeighbors =
allNeighbors |> List.filter (\( x, y ) -> x >= 0 && x < 5 && y >= 0 && y < 5)
in
validNeighbors
main : Html msg
main =
Html.text ("Lights on after update: " ++ toString (lightsOnCount (applyMoves moves state)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment