The weekly challenge 296 - Task 1: String Compression
1 #!/usr/bin/env perl
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 use strict;
46 use warnings;
47
48 foreach my $string ( ("abbc", "aaabccc", "abcc") ) {
49 print "Input: $string\n";
50 my $compressed = string_compression($string);
51 print "Output: $compressed\n";
52 print "Uncompressed: " . string_decompression($compressed) . "\n";
53 }
54
55 sub string_compression {
56 my $chars = shift;
57 my $count = 1;
58 my ($prev, @rest) = split //, $chars;
59 my $result = "";
60 while(@rest) {
61 my $next = shift @rest;
62 if($next eq $prev) {
63 $count++;
64 } else {
65 if($count > 1) {
66 $result .= "$count$prev";
67 $count = 1;
68 } else {
69 $result .= $prev;
70 }
71 $prev = $next;
72 }
73 }
74 if($count > 1) {
75 $result .= $count;
76 }
77 $result .= $prev;
78 return $result;
79 }
80
81 sub string_decompression {
82 my $input = shift;
83 my $result = "";
84 my $count;
85 while(length($input)) {
86 $count = 1;
87 if($input =~ m/^\d/) {
88 $input =~ s/(\d+)//;
89 $count = $1;
90 }
91 $input =~ s/^(.)//;
92 my $char = $1;
93 $result .= $char x $count;
94 }
95 return $result;
96 }