aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-022/ruben-westerberg/perl5/ch-2.pl87
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[$_];
+ }
}