loading...

re: Daily Challenge #8 - Scrabble Word Calculator VIEW POST

FULL DISCUSSION
 

Here's my solution in Perl, along with a few tests.

#!/usr/bin/env perl

use v5.24;
use strict;
use warnings;
use feature qw(signatures);
no warnings "experimental::signatures";
use List::Util qw(sum);
use Carp;

my %scores = (
    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,
);

my %multiplier = ( D => 2, T => 3 );

sub scrabble_score ($word) {
    $word = uc($word);
    my $score = 0;
    my $mult  = 1;
    my $count = 0;

    if ( $word =~ s/\((D|T)\)// ) {
        $mult = $multiplier{$1};
    }

    while ( $word =~ s/([[:alpha:]])(\^|\*{0,2})// ) {
        ++$count;
        $score += ( $2 ne '^' ) * ( $scores{$1} + $scores{$1} * length($2) );
    }

    return ( $score * $mult ) + 50*($count == 7);
}


use Test::More tests => 7;

my $word = "quintessential";
is( scrabble_score($word), 23, "Score for $word is 23" );
$word = "he*llo**";
is( scrabble_score($word), 11, "Score for $word is 11" );
$word = "quintessential(t)";
is( scrabble_score($word), 69, "Score for $word is 69" );
$word = "q^uintessential(t)";
is( scrabble_score($word), 39, "Score for $word is 39" );
$word = "he*llo**(d)";
is( scrabble_score($word), 22, "Score for $word is 22" );
$word = "he^llo**(d)";
is( scrabble_score($word), 18, "Score for $word is 18" );
$word = "wordier(d)";
is( scrabble_score($word), 72, "Score for $word is 72" );

Edit: fixed a bug, stray print, and added the 7 letter bonus

code of conduct - report abuse