diff options
| author | simon-dueck <126712673+simon-dueck@users.noreply.github.com> | 2023-03-28 14:11:38 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-03-28 14:11:38 -0500 |
| commit | 95c661a12b81513cdddc3977c02262668a58a68c (patch) | |
| tree | af9ce8905d92920b7c17e31b000440c8abced371 | |
| parent | 2b1861cb0e15fc0dba9900b294cd018effbf7d3f (diff) | |
| download | perlweeklychallenge-club-95c661a12b81513cdddc3977c02262668a58a68c.tar.gz perlweeklychallenge-club-95c661a12b81513cdddc3977c02262668a58a68c.tar.bz2 perlweeklychallenge-club-95c661a12b81513cdddc3977c02262668a58a68c.zip | |
Added solution for challenge 2
| -rw-r--r-- | challenge-210/simon-dueck/fsharp/ch-2.fsx | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/challenge-210/simon-dueck/fsharp/ch-2.fsx b/challenge-210/simon-dueck/fsharp/ch-2.fsx new file mode 100644 index 0000000000..1dde08cc63 --- /dev/null +++ b/challenge-210/simon-dueck/fsharp/ch-2.fsx @@ -0,0 +1,48 @@ +(*
+ You are given an array of integers which can move in right
+ direction if it is positive and left direction when negative.
+
+ If two numbers collide then the smaller one will explode.
+ And if both are same then they both explode.
+ We take the absolute value in consideration when comparing.
+
+ All numbers move at the same speed, therefore any 2 numbers
+ moving in the same direction will never collide.
+
+ Write a script to find out who survives the collision.
+*)
+
+let abs a = if a > 0 then a else 0 - a
+
+let collide a b: int option =
+ if (abs a) = (abs b) then None
+ elif (abs a) > (abs b) then Some(a)
+ else Some(b)
+
+let number_collision arr: int list =
+
+ let rec advance = function
+ | x::y::xs when x > 0 && y < 0 ->
+ match collide x y with
+ | Some(w) when w > 0 -> advance (w :: xs)
+ | Some(w) -> w :: (advance xs)
+ | None -> advance xs
+ | x::y::xs when x > 0 && y > 0 || x < 0 && y < 0 ->
+ x :: advance (y::xs)
+ | x -> x
+
+ let rec repeat arr =
+ let advanced = advance arr
+ if advanced = arr then advanced
+ else repeat advanced
+
+ repeat arr
+
+let a = [2; 3; -1;]
+printfn $"{number_collision a}"
+
+let b = [3; 2; -4;]
+printfn $"{number_collision b}"
+
+let c = [1; -1;]
+printfn $"{number_collision c}"
\ No newline at end of file |
