biohisham has asked for the wisdom of the Perl Monks concerning the following question:
I wanted to treat the list (1,0,9,15,6) as the number (109156)but I failed because the program output is@a=qw(1 0 9 15 6); @b=qw( 1 1 4 );
whereas the expected output (and the correct one), should have been1 0 9 15 6 1 1 4 __________+ 1 1 1 7 0 (which corresponds to the program logic)
I wanted to avoid converting the entire arrays to strings and instead pop an array element to a string one at a time and unshift a string to an array one at a time. How can I extend this logic to correspond to math rules and give me the desired output even if the sum of two opposite elements from an array were larger than 20 or 30..etc for that matter?. any suggestions would be cherished and any criticism is welcome too.here is my code, uncomment commented lines to try the different scenarios I thought of but only one case should be uncommmented at a time since I am using the same variable names for every different case of the three cases.1 0 9 15 6 1 1 4 __________+ 10 9 2 7 0 (which corresponds to the rules of math)
#!/usr/local/bin/perl use strict; use warnings; my (@a, @b, @result); my ($a_len, $b_len,$a, $b, $sum); @a=qw(1 0 9 15 6); #case1 when @a > @b @b=qw( 1 1 4 ); #@a = qw( 1 5 9); #case2 when @a < @b #@b = qw(10 9 3 6); #case3 when @a == @b #@a = qw(1 1 6 9 2); #@b = qw(2 1 4 4 8); $a_len = @a; #to make decisions on which case to follow $b_len = @b; print "@a\n"; print "@b\n"; print "__________+\n"; while(@a || @b){ if($a_len > $b_len){ $a = pop @a; $b= @b !=0? pop @b : 0; #pop $b or assign zero wher +e empty. $sum = $a + $b ; if($sum >= 10 && @a!=0){ $sum -=10; #assign to sum the ones posi +tion and strip the tens position. $a[-1]+=1; # add one to the following p +osition. } unshift @result, $sum; }elsif($a_len < $b_len){ $a= @a!=0? pop @a: 0; # pop $a or ass +ign zero where empty $b = pop @b; $sum = $a + $b ; if($sum >= 10 && @b !=0){ $sum -=10; $b[-1]+=1; } unshift @result, $sum; }else{ $a = pop @a; $b = pop @b; $sum = $a+$b; if($sum >= 10){ $sum -=10; $a[-1]+=1; } unshift @result, $sum; } } print "@result";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Arithmetical Simulation
by GrandFather (Saint) on Jul 31, 2009 at 01:41 UTC | |
by biohisham (Priest) on Jul 31, 2009 at 13:49 UTC | |
by GrandFather (Saint) on Jul 31, 2009 at 21:28 UTC | |
by biohisham (Priest) on Jul 31, 2009 at 22:48 UTC | |
by GrandFather (Saint) on Jul 31, 2009 at 23:05 UTC | |
| |
|
Re: Arithmetical Simulation
by plobsing (Friar) on Jul 31, 2009 at 02:50 UTC | |
by biohisham (Priest) on Jul 31, 2009 at 14:11 UTC | |
|
Re: Arithmetical Simulation
by tilly (Archbishop) on Jul 31, 2009 at 21:56 UTC |