RabbitFarm
2021-11-28
A Binary Addition Simulation / Nth from a Sorted Multiplication: Table The Weekly Challenge 140
The examples used here are from The Weekly Challenge problem statement and demonstrate the working solution.
Part 1
You are given two decimal-coded binary numbers, $a and $b. Write a script to simulate the addition of the given binary numbers.
Solution
use strict;
use warnings;
sub add_binary{
my($x, $y) = @_;
my $sum = "";
my @a = reverse(split(//, $x));
my @b = reverse(split(//, $y));
if(@b > @a){
my @c = @b;
@b = @a;
@a = @c;
}
my $carry = 0;
for(my $d = 0; $d <= @a - 1; $d++){
my $d0 = $a[$d];
my $d1 = $b[$d];
if($d1){
$sum = "0$sum", $carry = 0 if $d0 == 1 && $d1 == 1 && $carry == 1;
$sum = "1$sum", $carry = 0 if $d0 == 1 && $d1 == 0 && $carry == 0;
$sum = "0$sum", $carry = 1 if $d0 == 1 && $d1 == 1 && $carry == 0;
$sum = "0$sum", $carry = 1 if $d0 == 0 && $d1 == 1 && $carry == 1;
$sum = "0$sum", $carry = 0 if $d0 == 0 && $d1 == 0 && $carry == 0;
$sum = "1$sum", $carry = 0 if $d0 == 0 && $d1 == 0 && $carry == 1;
$sum = "0$sum", $carry = 1 if $d0 == 1 && $d1 == 0 && $carry == 1;
$sum = "1$sum", $carry = 0 if $d0 == 0 && $d1 == 1 && $carry == 0;
}
else{
$sum = "0$sum", $carry = 1, next if $d0 == 1 && $carry == 1;
$sum = "1$sum", $carry = 0, next if $d0 == 0 && $carry == 1;
$sum = "0$sum", $carry = 0, next if $d0 == 0 && $carry == 0;
$sum = "1$sum", $carry = 0, next if $d0 == 1 && $carry == 0;
}
}
$sum = "$carry$sum" if $carry == 1;
return $sum;
}
MAIN:{
print add_binary(11, 1) . "\n";
print add_binary(101, 1) . "\n";
print add_binary(100, 11) . "\n";
}
Sample Run
$ perl perl/ch-1.pl
100
110
111
Notes
I have an unusual fondness for Perl's right hand conditional. But that is pretty obvious from the way I wrote this, right?
Part 2
You are given 3 positive integers, $i, $j and $k. Write a script to print the $kth element in the sorted multiplication table of $i and $j.
Solution
use strict;
use warnings;
sub nth_from_table{
my($i, $j, $k) = @_;
my @table;
for my $x (1 .. $i){
for my $y (1 .. $j){
push @table, $x * $y;
}
}
return (sort {$a <=> $b} @table)[$k - 1];
}
MAIN:{
print nth_from_table(2, 3, 4) . "\n";
print nth_from_table(3, 3, 6) . "\n";
}
Sample Run
$ perl perl/ch-2.pl
3
4
Notes
Full Disclosure: At first I wanted to do this in some convoluted way for fun. After
experimenting with, like, nested map
s for a few minutes I lost all interest in "fun" and
just went with a couple of for
loops!
References
posted at: 17:16 by: Adam Russell | path: /perl | permanent link to this entry