in reply to Arithmetical Simulation
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. ;)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Arithmetical Simulation
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 | |
by biohisham (Priest) on Jul 31, 2009 at 23:44 UTC |