Skip to content

Instantly share code, notes, and snippets.

@bewuethr
Last active June 21, 2016 22:53
Show Gist options
  • Save bewuethr/ddc57740923744847918 to your computer and use it in GitHub Desktop.
Save bewuethr/ddc57740923744847918 to your computer and use it in GitHub Desktop.
Scrabble task from codingame - requires too much memory, but too nice to throw away
#!/usr/bin/perl
# Reads number of words $n from first line of input, the $n words and finally
# the scrabble letters provided. Using a smart grep and a Schwartzian Transform,
# the list of words is filtered (possible to be built from letters provided?)
# and then sorted by a) scrabble score and b) order of appearance in list.
use strict;
use warnings;
use 5.020;
use Array::Utils qw(array_minus);
use List::Util qw(reduce first);
chomp(my $n = <STDIN>);
my @words;
while ($n--) {
chomp(my $word = <STDIN>);
push @words, $word;
}
my %score_table = (
e => 1, a => 1, i => 1, o => 1,
n => 1, r => 1, t => 1, l => 1,
s => 1, u => 1, d => 2, g => 2,
b => 3, c => 3, m => 3, p => 3,
f => 4, h => 4, v => 4, w => 4,
y => 4, k => 5, j => 8, x => 8,
q => 10, z => 10,
);
chomp(my $letters = <STDIN>);
my @letters = split //, $letters;
my @top_words =
map { $_->[0] }
sort {
$b->[1] <=> $a->[1]
||
(first { $words[$_] eq $a->[0] } 0..$#words) <=> (first { $words[$_] eq $b->[0] } 0..$#words)
}
map {
my @letters = split //, $_;
my $sum = reduce { $a + $score_table{$b} } 0, @letters;
[$_, $sum];
}
grep {
my @word = split //, $_;
# Empty list means 'is subset' - turns out this isn't proper submultiset!
array_minus(@word, @letters) == 0;
} @words;
say $top_words[0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment