Peter’s blog ✴ Week 145 ✴ 27 December 2021

THE WEEKLY CHALLENGE
Dot product and palindromes

The Perl Camel

Task 1

Dot product

You are given 2 arrays of same size, @a and @b. Write a script to implement Dot Product.

Examples


Example 1:
@a = (1, 2, 3);
@b = (4, 5, 6);
$dot_product = (1 * 4) + (2 * 5) + (3 * 6) => 
   4 + 10 + 18 => 32

Analysis

This could be a one-liner, but for safety I check that the arrays are the same length, and then format the output to match Mohammad's example.

Perl Weekly’s review

from PW issue 545

Cool use of regex to find Palindromes. Thanks for sharing your knowledge with us.

Try it 

Try running the script with any input:



example: 1, 2, 3



example: 4, 5, 6

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2021-12-27
# PWC 145 task 1

use v5.20;
use warnings;
use strict;

my (@tests, $test, @a, @b, $j, $p, $dp, $string1, $string2);

@tests = ([[1, 2, 3], [4, 5, 6]], [[93, 72, 11], [-1, 1000, 0]], [[1, 2, 3, 4], [1, 2, 3]]);

for $test (@tests) {
    
    # extract arrays
    @a = @{$test->[0]};
    @b = @{$test->[1]};
    say qq[\n\@a = (] . join(', ', @a) . qq[)];
    say qq[\@b = (] . join(', ', @b) . qq[)];
    
    # check lengths
    if (scalar @a != scalar @b) {
        say 'Not the same length';
        next;
    }
    
    # make dot product and required output text
    $string1 = $string2 = '';
    $dp = 0;
    for $j (0 .. scalar @a - 1) {
        $p = $a[$j] * $b[$j];
        $dp += $p;
        $string1 .= qq[($a[$j] * $b[$j]) + ];
        $string2 .= qq[$p + ];
    }
    
    say '$dot_product = ' . substr($string1, 0, -2) . '=> ' . substr($string2, 0, -2) . qq[=> $dp];
        
}   
    

21 lines of code

Output from script


@a = (1, 2, 3)
@b = (4, 5, 6)
$dot_product = (1 * 4) + (2 * 5) + (3 * 6) => 4 + 10 + 18 => 32

@a = (93, 72, 11)
@b = (-1, 1000, 0)
$dot_product = (93 * -1) + (72 * 1000) + (11 * 0) => -93 + 72000 + 0 => 71907

@a = (1, 2, 3, 4)
@b = (1, 2, 3)
Not the same length

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain