The power of regular expressions in Perl


I’ve spent a lot of time playing challanges around the net. I started at first with http://www.osix.net/. Good site with some good challanges (I’m at no. 7 and I can’t figure out the code yet icon razz The power of regular expressions in Perl ). After you solve a challange you get to look at other people solutions to that particular challange. So as I finish the following challange:

There is a “mathematical” pyramid with the following pattern:
1
11
21
1211
111221
312211
Each row of the pyramid is created by reading the row above it, i.e.:”one”
“one one”
“two ones”
“one two” “one one”
“one one” “one two” “two ones”
“three ones” “two twos” “one one”
Your task is to write a program to calculate the 44th line of this pyramid. Once you have found that last line, add up the values of all of its digits, and that will be your solution.

with the code below:

#!/usr/bin/perl -w

$line = 2;
$first = 1;
while ($line <=44) {
@array = split(//,$first);
$size = $#array;
$counter = 0;
@final = ();
while ($counter <= $size) {

if ($counter == 0){
push(@test,$array[$counter]);
push(@test,1);

}
else {
if ($test[0] == $array[$counter]) {
$test[1]++;
#print “$test[0] $test[1]\n”;
}
else {
push(@final,$test[1]);
push(@final,$test[0]);
@test = ();
undef(@test);
push(@test,$array[$counter]);
push(@test,1);

}
}

$counter++;

}
push(@final,$test[1]);
push(@final,$test[0]);

$size1 = $#final;
$counter = 0;
undef $first;
$sum = 0;
while ($counter <= $size1) {
$sum += $final[$counter];
$first .= $final[$counter];
$counter++;
}
$line++;
@final=();
@test=();
$counter = 0;
}
print “\n Suma: $sum \n”;

I took a look at how others completed this challange. I know my code it’s not eaven near perfect and it was done on the run sort of speek but browsing through the sollutions I’ve found this one..the perfect code you might wanna call it for this challange.. the power of regular expression:

#!/usr/bin/perl -w
use strict;

my $v = ’1′;
for (1..43) {
$v =~ s/((.)2*)/length($1) . $2/eg;
}

my $count = 0;
$count += chop $v while $v;
print “$count\n”;

Tags:

Daca vrei sa vezi ce-i mai trece prin cap suricatei in continuarea, aboneaza-te la RSS.


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!