aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcorvettes13 <86648326+corvettes13@users.noreply.github.com>2021-11-25 03:50:38 -0600
committerGitHub <noreply@github.com>2021-11-25 03:50:38 -0600
commitf2a40d26b1be9a34d675653de17c6abc215af004 (patch)
tree3ddc2f5cd92179e1a1507e355f8a165930e74deb
parentb81cafbb9326efe10251a65de7a8a154fd32b30b (diff)
downloadperlweeklychallenge-club-f2a40d26b1be9a34d675653de17c6abc215af004.tar.gz
perlweeklychallenge-club-f2a40d26b1be9a34d675653de17c6abc215af004.tar.bz2
perlweeklychallenge-club-f2a40d26b1be9a34d675653de17c6abc215af004.zip
Create ch-1.pl
-rw-r--r--challenge-140/paul-fajman/perl/ch-1.pl70
1 files changed, 70 insertions, 0 deletions
diff --git a/challenge-140/paul-fajman/perl/ch-1.pl b/challenge-140/paul-fajman/perl/ch-1.pl
new file mode 100644
index 0000000000..1803836cb7
--- /dev/null
+++ b/challenge-140/paul-fajman/perl/ch-1.pl
@@ -0,0 +1,70 @@
+#!/usr/bin/perl
+
+# Weekly Challenge 140 Task 1
+#
+# You are given two decimal-coded binary numbers, $a and $b.
+#
+# Write a script to simulate the addition of the given binary numbers.
+#
+# The script should simulate something like $a + $b. (operator overloading)
+
+use strict;
+
+my ($a, $b, $c, $final);
+my @test = qw (11 1 101 1 100 11);
+
+for ($c=0; $c<$#test+1; $c+=2) {
+ $a = $test[$c];
+ $b = $test[$c+1];
+
+ $final = binary_add($a, $b);
+ print "Input: \$a = $a; \$b = $b\n";
+ print "Output: $final\n\n";
+}
+
+sub binary_add {
+ my $x = shift;
+ my $y = shift;
+
+# Determine which number is larger
+ my $diff = length($x) - length($y);
+ my ($sum, $num, $i);
+ my (@arr1, @arr2, @num);
+ my $carry=0;
+
+# Append left with 0s to help with piecewise math.
+ if ($diff > 0) {
+ $diff = length($x);
+ $y = sprintf("%0${diff}d", $y);
+
+ }
+ elsif ($diff < 0) {
+ $diff = length($y);
+ $x = sprintf("%0${diff}d", $x);
+ }
+
+# Split numbers into pieces
+ @arr1=split(//,$x);
+ @arr2=split(//,$y);
+ for ($i=$#arr1; $i>-1;$i--) {
+ $sum=$arr1[$i]+$arr2[$i]+$carry;
+
+# If/elses to ensure no values greater than 1.
+ if ($sum eq 2) {
+ $sum = 0;
+ $carry = 1;
+ }
+ elsif ($sum eq 3) {
+ $sum = 1;
+ $carry = 1;
+ }
+ else {
+ $carry = 0;
+ }
+ $num=$sum.$num
+ }
+
+# One last check for a carry.
+ $num="1".$num if $carry eq 1;
+ return "$num";
+}