diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2021-09-07 03:35:11 +0100 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2021-09-07 03:35:11 +0100 |
| commit | 7e18b8378d8e1dacaba741df7f50c7660770ca1c (patch) | |
| tree | b9d68ca7b4c2af2b53b14dca3ab4a82dcc45f999 /challenge-129 | |
| parent | c37839003cb9c0805f33d120e1949fdf4b1b9246 (diff) | |
| download | perlweeklychallenge-club-7e18b8378d8e1dacaba741df7f50c7660770ca1c.tar.gz perlweeklychallenge-club-7e18b8378d8e1dacaba741df7f50c7660770ca1c.tar.bz2 perlweeklychallenge-club-7e18b8378d8e1dacaba741df7f50c7660770ca1c.zip | |
- Added solution by Peter Campbell Smith.
Diffstat (limited to 'challenge-129')
| -rwxr-xr-x | challenge-129/peter-campbell-smith/perl/ch-2.pl | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/challenge-129/peter-campbell-smith/perl/ch-2.pl b/challenge-129/peter-campbell-smith/perl/ch-2.pl new file mode 100755 index 0000000000..6b6837eec9 --- /dev/null +++ b/challenge-129/peter-campbell-smith/perl/ch-2.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl + +# Peter Campbell Smith - 2021-09-06 +# Perl weekly challenge 129 task #2 + +# You are given two linked list having single digit positive numbers. + +# Write a script to add the two linked list and create a new linked +# representing the sum of the two linked list numbers. The two linked +# lists may or may not have the same number of elements. + +use strict; +use warnings; + +my ($L1, $L1_left, $L2, $L2_left, $L3, $one, $two, $carry, $sum, $units, $blanks1, $blanks2); + +# given lists +$L1 = $L1_left = '9 -> 2 -> 0 -> 0 -> 5 -> 0 -> 7 -> 0'; +$L2 = $L2_left = '7 -> 9 -> 9 -> 0 -> 8 -> 3 -> 9 -> 7 -> 0'; + +# cycle back from the end of each list +$carry = 0; +$L3 = ''; +while ($L1_left =~ m|\d| or $L2_left =~ m|\d| or $carry) { # not finished yet + $one = $two = 0; + ($L1_left, $one) = ($1, $2) if $L1_left =~ m|(.*)(\d)|; # strip off last (remaining) digit of each list + ($L2_left, $two) = ($1, $2) if $L2_left =~ m|(.*)(\d)|; + $sum = $one + $two + $carry; # add the two digits and any carryover + $units = $sum % 10; # get new digit + $L3 = "$units -> $L3"; # add it to the start of L3 + $carry = ($sum - $units) / 10; # and compute any carryover (can only be 0 or 1) +} + +# line them up +$L3 =~ s|....$||; # remove final ' -> ' +$blanks1 = length($L3) - length($L1); +$blanks2 = length($L3) - length($L2); +print 'L1 = ' . (' ' x $blanks1) . $L1 . "\n" . + 'L2 = ' . (' ' x $blanks2) . $L2 . "\n" . + "L3 = $L3\n"; |
