[QWERT] Locate non-zero numbers start and end from a string of numbers
Input is a string of numbers:
0012300123400012012311
Output will list the none-zero numbers' start and length.
Perl语言: 高亮代码由发芽网提供
my $nums = shift;
my $output = &cluster($nums);
print $output . "\n";
sub cluster{
my $nums = $_[0];
my @nums = (split //,$nums);
my $indicator = 0;
my $len = 0;
my $start= 0;
my $lens = '';
my $starts= '';
foreach my $n (0..@nums-1){
if ($nums[$n]>0){
$len++;
if ($indicator==0 || $num = @nums -1){
$start = $n;
$indicator =1;
}
}
elsif ( $nums[$n]<=0 ) {
if ( $indicator==1) {
$starts = $starts . $start . ",";
$lens = $lens . $len . ",";
$len = 0;
$indicator =0;
}
}
}
return ($starts . "\t" . $lens );
}
my $output = &cluster($nums);
print $output . "\n";
sub cluster{
my $nums = $_[0];
my @nums = (split //,$nums);
my $indicator = 0;
my $len = 0;
my $start= 0;
my $lens = '';
my $starts= '';
foreach my $n (0..@nums-1){
if ($nums[$n]>0){
$len++;
if ($indicator==0 || $num = @nums -1){
$start = $n;
$indicator =1;
}
}
elsif ( $nums[$n]<=0 ) {
if ( $indicator==1) {
$starts = $starts . $start . ",";
$lens = $lens . $len . ",";
$len = 0;
$indicator =0;
}
}
}
return ($starts . "\t" . $lens );
}