biohisham has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks, over the last few days I had this idea of writing a program that simulates the arithmetic addition on paper but with the strict condition that arrays for the numbers and the result should be the feeding and output mechanisms of the program, I somewhat succeeded at making the program work for the cases where either one of the arrays is longer than the other one and where both arrays are of the same length (much wrangling was involved btw). The program seems to work fine after all, it adds two numbers together and where the summation is >= 10 it carries over 1 to the following position to be evaluated. My very humble logical abilities crashed at this situation, an example:
@a=qw(1 0 9 15 6); @b=qw( 1 1 4 );
I wanted to treat the list (1,0,9,15,6) as the number (109156)but I failed because the program output is
1 0 9 15 6 1 1 4 __________+ 1 1 1 7 0 (which corresponds to the program logic)
whereas the expected output (and the correct one), should have been
1 0 9 15 6 1 1 4 __________+ 10 9 2 7 0 (which corresponds to the rules of math)
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.
#!/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";
Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind

Replies are listed 'Best First'.
Re: Arithmetical Simulation
by GrandFather (Saint) on Jul 31, 2009 at 01:41 UTC

    There are several solutions to your problem. They are all different ways of preprocessing your data so that it is in a suitable state for the main algorithm. Ultimately they use the facility of split with an empty string to generate a list of single characters. You can either provide your input data as a number in string, or convert your array to a string (using join most likely), then use split to create a clean list of digits:

    my @number = split '', '1234567';

    However with a little more preprocessing the actual addition logic becomes much simpler. Consider:

    use strict; use warnings; my @numbers = map {[reverse split '']} qw(109156 114); my $maxDigits = 0; @$_ > $maxDigits and $maxDigits = @$_ for @numbers; @numbers = map {[@$_, (0) x ($maxDigits - @$_)]} @numbers; my @result; my $carry; for my $digit (0 .. $maxDigits - 1) { my $sum = $carry; $sum += $_->[$digit] for @numbers; push @result, substr $sum, -1, 1, ''; $carry = $sum || 0; } @numbers = map {[reverse @$_]} @numbers; @result = reverse @result; print "@$_\n" for @numbers; print '-' x ($maxDigits * 2), "\n"; print "@result\n";

    Prints:

    1 0 9 1 5 6 0 0 0 1 1 4 ------------ 1 0 9 2 7 0

    Suppressing the leading zeros is left as an exercise for the reader. ;)


    True laziness is hard work
      I considered preprocessing, but that would have me involving in posing restriction to the flexibility of feeding any number larger than 9 to a certain array position (or so thought I). You have actually made justice to this situation, so thankful I am indeed, I think preprocessing should be considered, however, I wished your answer was more commented, I am still in the start of learning Perl the right way so some advanced things require someone opening my eyes for me and directing my attention there, there are some places in your reply where I could not understand the concept because some things I faced them first time, like this line
      @$_ > $maxDigits and $maxDigits = @$_ for @numbers;
      I mean the @$_ to be specific.....Thank you and ++ , I will of course read about it and learn it :)
      Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind

        I must admit that some of my intent was to make you look hard at the code and think and about how it works. I hope that the variable names convey the intent of the code even if the mechanism is not obvious for someone starting out.

        $_ is of course the default variable. The line

        my @numbers = map {[reverse split '']} qw(109156 114);

        generates two entries in @numbers. Each entry is an array of the digits in the number with the order from least significant digit to most significant.

        @$_ > $maxDigits and $maxDigits = @$_ for @numbers;

        iterates over the numbers (which are stored as arrays of digits remember) and sets $_ to the reference to each digit array in turn. Thus @$_ is the array of digits in the current array which in scalar context is simply the number of digits.

        The other trick there is using an and in place of an if to have the assignment only happen if the current number of digits is greater than $maxDigits. Use this particular trick sparingly. I only used it here to avoid using a full for loop rather than for as a statement modifier. Nested statement modifiers are not allowed.

        For bonus points, can you see the bug in the code?

        Did you notice that you can provide any number of numbers?

        Would a short comment have conveyed that information? Would a long comment be useful when you have progressed to the point of recognising @$_? In general comments of that nature should be avoided - at best they obscure the actual code and at worst they may be wrong. In either case they double the effort of maintenance. It is much better to use good identifiers and code structure to convey the intent of code with comments used to provide information about interaction between different parts of the code and other 'global' information that can not be gleaned from the code itself.


        True laziness is hard work
Re: Arithmetical Simulation
by plobsing (Friar) on Jul 31, 2009 at 02:50 UTC

    I'm not sure how you add on paper, but for me, I only ever consider one digit of the number at a time. From my perspective, the problem is that your inputs can be arbitrary numbers, not just digits.

    To get all elements to be digits, you can:

    • work in a base greater than the largest element (changes the rules, feels like cheating)
    • preprocess the arrays
    • treat the elements with more care when you pop them
    Here's an example of the last approach:

    #!/usr/local/bin/perl use strict; use warnings; use constant BASE => 10; run( @$_ ) for ( [ 'case1 when @a > @b', [qw(1 0 9 15 6)], [qw( 1 1 4 )], ], [ 'case2 when @a < @b', [qw( 1 5 9)], [qw(10 9 3 6)], ], [ 'case3 when @a == @b', [qw(1 1 6 9 2)], [qw(2 1 4 4 8)], ] ); sub run { my ($msg, $a, $b) = @_; local $\ = "\n"; # or use say on 5.10 print "# $msg"; print "@$a"; print "@$b"; print "__________+"; my @result = add( $a, $b ); print "@result"; print ""; } { use integer 'division'; sub add { my ($a, $b) = @_; my @sum; my $carry = 0; while (@$a || @$b || $carry) { my $_a = rem_lsd($a); my $_b = rem_lsd($b); my $sum = $_a + $_b + $carry; $carry = $sum / BASE; $sum %= BASE; unshift @sum, $sum; } return @sum; } # get (remove) least significant digit # corrects for multidigit inputs (by removing the lsd from the las +t element) # returns zero when array is empty sub rem_lsd { my $elem = pop @{$_[0]} || 0; # put back extra digits if (my $extra = $elem / BASE) { push @{$_[0]}, $extra; } $elem %= BASE; return $elem; } }
      Thanks very much for the generous explanation, this is just it, esp using the base to decide the value of $carry... I will try something similar of a combination of grandfather reply and this one here.
      Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind
Re: Arithmetical Simulation
by tilly (Archbishop) on Jul 31, 2009 at 21:56 UTC
    A useful tip that may save you a lot of headaches.

    Have (1,0,9,1,5,6) represent the number 651901. That means that $number[$i] is the 10**$i constant and makes lining things up much easier. You'll need to throw in random reverses, but it makes everything else make more sense.

    When you're done you may wish to read the code to my (semi-joke) module Math::Fleximal which does something very much like this. (But not necessarily in base 10. Though it can work in base 10.)