The Weekly Challenge - 401

TASK #2: Reconstruct Digits
You are given a string containing an out-of-order English representation of digits 0-9.

Write a script to return the digits in ascending order.

#!/usr/bin/perl
use strict;
use warnings;

sub count_letter {
    my ($str, $letter) = @_;

    my $count = () = $str =~ /$letter/g;

    return $count;
}

sub remove_word {
    my ($str, $word) = @_;

    for my $letter (split //, $word) {

        my $pos = index($str, $letter);

        return undef if $pos == -1;

        substr($str, $pos, 1, "");
    }

    return $str;
}

sub reconstruct_result {
    my (@count) = @_;

    return join "", map {
        $_ x $count[$_]
    } 0 .. 9;
}

sub reconstruct_digits {

    my ($str) = @_;

    return "Invalid string"
        unless defined $str && $str =~ /^[a-z]+$/;

    my @order = (

        # Each entry contains:
        # 1. A unique letter that identifies a digit.
        # 2. The English word representing that digit.
        # The array is deliberately ordered by recognition priority!

        [z => "zero"],   # Digit 0: 'z' appears only in zero.
        [w => "two"],    # Digit 2: 'w' appears only in two.
        [u => "four"],   # Digit 4: 'u' appears only in four.
        [x => "six"],    # Digit 6: 'x' appears only in six.
        [g => "eight"],  # Digit 8: 'g' appears only in eight.
        [h => "three"],  # Digit 3: 'h' appears only in three.
        [f => "five"],   # Digit 5: 'f' appears only in five.
        [v => "seven"],  # Digit 7: 'v' appears only in seven.
        [i => "nine"],   # Digit 9: 'i' appears only in nine.
        [o => "one"]     # Digit 1: 'o' appears only in one.
    );

    my %digit = (
        zero => 0, one => 1, two => 2,
        three => 3, four => 4, five => 5,
        six => 6, seven => 7, eight => 8,
        nine => 9
    );

    # Create an array with 10 elements, all initialized to 0.
    my @count = (0) x 10;

    for my $item (@order) {

        my ($key, $word) = @$item;

        # Count the identifying letter.
        my $n = count_letter($str, $key);

        # Store the count.
        $count[$digit{$word}] = $n;

        # Remove the corresponding digit words.
        for (1 .. $n) {
            $str = remove_word($str, $word);

            return "Invalid string" unless defined $str;
        }
    }

    return "Invalid string" if length($str) > 0;

    return reconstruct_result(@count);
}

# Tests

my @examples = (
    "zroezerotwotwotwo",
    "sveeeinght",
    "onenineninefive",
    "zeroonetwothreeeightfivesixsevenninefour",
    "ninenineninenine",
    "abcdefgh"
);

for my $str (@examples) {

    print "$str => ", reconstruct_digits($str), "\n";
}

# Output:

# zroezerotwotwotwo => 00222
# sveeeinght => 78
# onenineninefive => 1599
# zeroonetwothreeeightfivesixsevenninefour => 0123456789
# ninenineninenine => 9999
# abcdefgh => Invalid string