ELM : How to find Intersection Point in 2D Grid?
Making a 2D Grid. Using X and Y axis. Inputs are a predetermined string called "instructions". I got some very helpful assistance on my elm code, and managed to solve my first function ( How to find final position) from a string of inputs.
I been working on the second function ( How to find intersection point ) and haven't found a solid solution. I think I'm almost there. Can someone help me with my intersection function in this 2D grid program?
At the moment compiled program outputs:
Final Position: { x = 2, y = 4 }
Intersection (position appear twice): { x = 0, y = 1 }
Final is correct. But the intersection point should be x = 2, y = 2 , Instructions tells it to go up 2 times "^^" then three steps right ">>>" and one step left. meaning the "snake" bites its own tail. Now it only looks at the first "char". ^ and not the rest.
Live code can be found here :
https://ellie-app.com/M76VPyJTLYa1
import Html exposing (Html)
type alias Location =
{ x : Int
, y : Int
}
instructions : String
instructions =
"^^>>><^>>>^<^v<v^^vv^><<"
firstInstruction : Char
firstInstruction =
instructions
|> String.toList
|> List.head
|> Maybe.withDefault '_'
main : Html msg
main =
let
initLoc =
{ x = 0, y = 0 }
finalLocation =
toString (calculateFinalLocation instructions initLoc)
firstIntersection =
toString (calculateIntersection firstInstruction initLoc)
in
Html.div []
[ Html.p [] [ Html.text ("Final: " ++ finalLocation) ]
, Html.p [] [ Html.text ("1st: " ++ firstIntersection) ]
]
// First Function ( Working )
calculateFinalLocation : String -> Location -> Location
calculateFinalLocation actions loc =
actions
|> String.toList
|> List.foldl calculateIntersection loc
// Second Function ( Gives wrong values )
calculateIntersection : Char -> Location -> Location
calculateIntersection action loc =
case action of
'^' ->
{ x = loc.x, y = loc.y + 1 }
'v' ->
{ x = loc.x, y = loc.y - 1 }
'>' ->
{ x = loc.x + 1, y = loc.y }
'<' ->
{ x = loc.x - 1, y = loc.y }
_ ->
loc