changeset 74:41c7cd909218

Write up exercises for Erlang day 2 (including bonus Tic Tac Toe)
author IBBoard <dev@ibboard.co.uk>
date Sat, 03 Feb 2018 19:53:28 +0000
parents 74976fddd25f
children 2df568aae515
files 5-Erlang/day2.erl
diffstat 1 files changed, 58 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/5-Erlang/day2.erl	Sat Feb 03 19:53:28 2018 +0000
@@ -0,0 +1,58 @@
+-module(day2).
+-export([find_tuple/2]).
+-export([calc_prices/1]).
+-export([score_tictactoe/1]).
+-export([has_won/2]).
+
+% Do a more Erlang-esque "crash if not matched" behaviour rather than an atom of "undefined" or "null"
+find_tuple([{Key, Value}|_], Key) -> Value;
+find_tuple([{_,_}|Tail], Key) -> find_tuple(Tail, Key).
+
+calc_prices(ProductList) -> [{Item, Quantity * Price} || {Item, Quantity, Price} <- ProductList].
+
+has_won(Board, P) ->
+    case Board of
+        { P, P, P,
+          _, _, _,
+          _, _, _ } -> true;
+
+        { _, _, _,
+          P, P, P,
+          _, _, _ } -> true;
+
+        { _, _, _,
+          _, _, _,
+          P, P, P } -> true;
+
+        { P, _, _,
+          P, _, _,
+          P, _, _ } -> true;
+
+        { _, P, _,
+          _, P, _,
+          _, P, _ } -> true;
+
+        { _, _, P,
+          _, _, P,
+          _, _, P } -> true;
+
+        { P, _, _,
+          _, P, _,
+          _, _, P } -> true;
+
+        { _, _, P,
+          _, P, _,
+          P, _, _ } -> true;
+          
+        _ -> false
+    end.
+
+score_tictactoe(Board) -> 
+    State = { has_won(Board, x), has_won(Board, o), lists:any(fun(Val) -> Val == b end, tuple_to_list(Board)) }, 
+    case State of
+        { true, false, _ } -> x;
+        { false, true, _ } -> o;
+        { _, _, true } -> no_winner;
+        { false, false, false } -> cat
+        % And { true, true, false } exceptions as it is invalid
+    end.
\ No newline at end of file