in reply to Find Length Of Longest Ascending/Descending Sequence
#!/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.
|
|---|