DEV Community

Discussion on: Daily Challenge #8 - Scrabble Word Calculator

Collapse
 
stevemoon profile image
Steve Moon • Edited

Erlang:

-module(devto8).
-export([scrabble_score/1]).

scrabble_score(Input) ->
    LS = #{$a => 1, $b => 3, $c => 3, $d => 2, $e => 1, $f => 4, $g => 2, $h => 4,
           $i => 1, $j => 8, $k => 5, $l => 1, $m => 3, $n => 1, $o => 1, $p => 3,
           $q => 10, $r => 1, $s => 1, $t => 1, $u => 1, $v => 4, $w => 4, $x => 8,
           $y => 4, $z => 10},
    LCInput = string:lowercase(Input),
    score_word(LS, LCInput, []).

score_word(_, [], Scores) when length(Scores) == 7 ->
    score_sum(Scores) + 50;
score_word(_, [$(,$t,$)], Scores) when length(Scores) == 7 ->
    score_sum(Scores) * 3 + 50;
score_word(_, [$(,$d,$)], Scores) when length(Scores) == 7 ->
    score_sum(Scores) * 2 + 50;
score_word(_, [$(,$t,$)], Scores) ->
    score_sum(Scores) * 3;
score_word(_, [$(,$d,$)], Scores) ->
    score_sum(Scores) * 2;
score_word(_, [], Scores) ->
    score_sum(Scores);
score_word(LS, [$^, _ | Rest], Scores) ->
    score_word(LS, Rest, Scores ++ 0);
score_word(LS, [Letter, $*, $* | Rest], Scores) ->
    score_word(LS, Rest, Scores ++ [maps:get(Letter,LS) * 3]);
score_word(LS, [Letter, $* | Rest], Scores) ->
    score_word(LS, Rest, Scores ++ [maps:get(Letter,LS) * 2]);
score_word(LS, [Letter | Rest], Scores) ->
    score_word(LS, Rest, Scores ++ [ maps:get(Letter, LS)]).

score_sum(Scores) ->
    lists:foldl(fun(X, Sum) -> X + Sum end, 0, Scores).
devto8:scrabble_score("z**z**z**z**z**z**z**(t)").
680

devto8:scrabble_score("thiswasfun").
19
Collapse
 
deciduously profile image
Ben Lovy

Ah, neat. Pattern matching was definitely the way to go about it functionally, wish I'd done that instead!