diff options
| author | Ruben Westerberg <drclaw@mac.com> | 2019-08-24 22:10:04 +1000 |
|---|---|---|
| committer | Ruben Westerberg <drclaw@mac.com> | 2019-08-24 22:10:04 +1000 |
| commit | 478d87cdf94e902f1fc01d4e42d0767a635940a6 (patch) | |
| tree | dd39d9322088eddc0eb8dabda87c76c905b8f5d1 | |
| parent | 84014b58431f94d05607621f5be85454799a6f7d (diff) | |
| download | perlweeklychallenge-club-478d87cdf94e902f1fc01d4e42d0767a635940a6.tar.gz perlweeklychallenge-club-478d87cdf94e902f1fc01d4e42d0767a635940a6.tar.bz2 perlweeklychallenge-club-478d87cdf94e902f1fc01d4e42d0767a635940a6.zip | |
A more tidy solution to ch-2.pl
| -rwxr-xr-x | challenge-022/ruben-westerberg/perl5/ch-2.pl | 87 |
1 files changed, 43 insertions, 44 deletions
diff --git a/challenge-022/ruben-westerberg/perl5/ch-2.pl b/challenge-022/ruben-westerberg/perl5/ch-2.pl index aa504468d6..694883c4fe 100755 --- a/challenge-022/ruben-westerberg/perl5/ch-2.pl +++ b/challenge-022/ruben-westerberg/perl5/ch-2.pl @@ -4,55 +4,54 @@ use warnings; use v5.26; # implement LZW -my @symbols= 'A'..'Z'; -my @indexes; -for (split "","TOBEORNOTTOBEORTOBEORNOT") { - my $res=encode(\@symbols, $_); - if ($res) { - push @indexes, $res - } -} -my $res=encode(\@symbols, $_); -if ($res) { - push @indexes, $res -} -print join ",",@indexes; +my @input=split "", $ARGV[0]//"TOBEORNOTTOBEORTOBEORNOT"; +my @decoded; +my @encoded; +my @symbols; + +print "Input: ",join("",@input),"\n"; +encode(\@symbols, \@input ,\@encoded); + +print "Encoded: ",join(",",@encoded),"\n"; + +decode(\@symbols,\@encoded,\@decoded); + +print "Decoded: ",join("",@decoded),"\n"; + + -for (@indexes) { - print decode(\@symbols,$_),"\n"; -} sub encode { - state $symbol=""; - my $dict=shift; - state $count= @$dict; - my $next=shift; - $symbol.=$next if defined $next; - print "Symbol: ",$symbol,"\n"; - state $prev=""; - print "Prev: ",$prev,"\n"; - my $s=(grep {$symbol eq $_} @$dict)[0]; - print "$s\n"; - print "$symbol\n"; - my $res; - if (defined $s and $next) { - #found existing keep adding - $res=undef; - } - else { - #add new symbol - print "New symbol $symbol\n"; - #$$dict{$symbol}=$count++; - push @$dict, $symbol; - $res=(grep {$prev eq $$dict[$_]} 0..@$dict-1)[0]; - $symbol=substr $symbol, -1; + my ($dict,$in, $out)=@_; + @$dict= ((0..9),('A'..'Z'),('a'..'z')); + push @$in, undef; + for (@$in) { + state $symbol=""; + state $count= @$dict; + my $next=$_;#shift; + $symbol.=$next if defined $next; + state $prev=""; + my $s=(grep {$symbol eq $_} @$dict)[0]; + my $res; + if (defined $s and $next) { + #found existing keep adding + $res=undef; + } + else { + #add new symbol + #$$dict{$symbol}=$count++; + push @$dict, $symbol; + $res=(grep {$prev eq $$dict[$_]} 0..@$dict-1)[0]; + push @$out, $res; + $symbol=substr $symbol, -1; + } + $prev=$symbol; } - $prev=$symbol; - $res; } sub decode { - my $dict=shift; - my $code=shift; - @$dict[$code]; + my ($dict,$in,$out)=@_; + for (@$in) { + push @$out, @$dict[$_]; + } } |
