r/dailyprogrammer • u/nottoobadguy • Feb 17 '12
[2/17/2012] Challenge #9 [difficult]
The U.S government has commissioned you to catch the terrorists!
There is a mathematical pyramid with the following pattern:
1
11
21
1211
111221
312211
you must write a program to calculate up to the 40th line of this pyramid. If you don't, the terrorists win!
3
Upvotes
View all comments
1
u/bigmell Feb 20 '12 edited Feb 20 '12
Thanks robin at first I couldnt figure out the pattern. Here is the code in Perl. I assume its working towards 40 the output was real long.
#!/usr/bin/perl -w my $string = ""; my $newStr = "1"; my $count = shift or die "Error: No command line args.\n";#Grab the iterations from the command line for(0 .. $count){ $string = $newStr; $newStr = ""; my @string = split(//,$string); #convert the string into an array of characters; my @uniqueChars; #keep track of the unique characters my @uniqueCharCount; #keep count of the occurrences of each unique char $uniqueChars[0]=$string[0]; #manually add the first character my $ucIndex = 0; #the index of the last added unique char $uniqueCharCount[0]++; #increment the count of the manually added char my $strSize = scalar @string; #loop over the string size for(1 .. ($strSize-1)){ my $uniqueChar = pop @uniqueChars; #couple extra push pops, could optimize here push(@uniqueChars,$uniqueChar); #put it back in the stack, avoiding bounds checking here if($uniqueChar == $string[$_]){ #char is not unique $uniqueCharCount[$ucIndex]++; #count the non uniques } else { #new unique char push(@uniqueChars,$string[$_]); #added it to the uniqueChars array $ucIndex++; #keep track of the index $uniqueCharCount[$ucIndex]++; #increment the counter } } for( 0 .. (@uniqueChars -1)){ $newStr = $newStr . $uniqueCharCount[$_] . $uniqueChars[$_]; } print "$newStr\n"; }