A little late to the party, but I didn't see any other posts that leveraged the cyclical nature of Z
10, so seemed worth putting in my two cents. Should be pretty efficient as well, given the once-through approach.
#!/usr/bin/perl -w
use strict;
while (<DATA>) {
chomp;
my $max = 0;
my $count = 1;
my $direction = 0;
my $last = substr $_, 0, 1;
for my $this (split //) {
local $_ = $this - $last;
++$count and next if $direction and $_ % 10 == $direction;
$count = 2 if $direction = abs==1 || abs==9 ? $_ % 10 : 0;
} continue {
$max = $max > $count ? $max : $count;
$last = $this;
}
print "$_\t=> $max\n";
}
__DATA__
82665409266027476709324472
2468
2345678
78901
78909
32109
32101
909
09090
outputs
82665409266027476709324472 => 3
2468 => 1
2345678 => 7
78901 => 5
78909 => 4
32109 => 5
32101 => 4
909 => 2
09090 => 2
Update: Ambrus caught a mistake in my $direction assignment for the case of 909. Corrected bugs (changed $this <=> $last to $_ % 10) and added cases to test set.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.