0

I am facing some problem while adding values in numeric string:

I have string that looks like 02:03:05:07:04:06. All the numbers have to be <10. Now, I have to take a random number from 1-9 and add that number with last position number of the string (e.g. 3).

I the sum>10, then I have add that number to the number in the second last position.

So far, I have

#!/usr/bin/perl -w
use strict;
my $str='02:03:05:07:04:06';
my @arr=split(/:/,$str);
my @new_arr=pop(@arr);
my $rand_val=int(rand(9));
my $val=$new_arr[0]+$rand_val;
if($val>=10)
{
   I am unable to generate a logic here:(

}

Please help me out of this problem.

After adding the number we have to join the string and print it also :)

4

4 に答える 4

1
my $str = '02:03:05:07:04:06';
my @nums = split /:/, $str;
my $add = int(rand(9)) + 1;
my $overflow = 1;
for (1..@nums) {
   if ($num[-$_] + $add < 10) {
      $num[-$_] += $add;
      $overflow = 0;
      last;
   }
}

die "Overflow" if $overflow;

$str = join ':', map sprintf('%02d', $_), @nums;
于 2013-01-15T20:44:01.673 に答える
0

I just run this and it works. The caveat is that, the lower the last number of the string is, the smaller the chance the "if ($val>=10)" will be valid

于 2013-01-15T20:45:25.423 に答える
0

This doesn't solve the problem of your rand_val potentially being 0, but I'll leave that as a task for you to resolve. This should give you what you're looking for in terms of traversing through the values in the array until the the sum of the random value and current most-last value in the array.

1  use strict;
2  my $str='02:03:05:07:04:06';
3  my @arr=split(/:/,$str);
4  my $rand_val=int(rand(9));
5  my $val;
6 
7  foreach my $i (reverse @arr){
8    $val = $i + $rand_val;
9    next if ($val >= 10);
10   print "val: $val, rand_val: $rand_val, value_used: $i\n";
11   last if ($val < 10);
12 }
于 2013-01-15T20:51:43.387 に答える
-1

I see a misstake : you do

my @new_arr=pop(@arr);
(...)
my $val=$new_arr[0]+$rand_val;

but pop only returns the last element, not a list.

于 2013-01-15T20:28:37.233 に答える