Divisible Average & String Difference
You are given an array of positive integers. Write a script to return the closest integer to the mean value of all even integers that are divisible by 3. If none is divisible, return 0.
An integer is both even and divisible by 3 if and only if it is divisible by 6:
num % 6 == 0.0.sum / count to the nearest integer.Runs in O(n) time and O(1) extra space.
#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
use Test::More;
signature_for divisible_average => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub divisible_average ($arr) {
my $sum = 0;
my $count = 0;
for my $num ( @{$arr} ) {
if ( $num % 6 == 0 ) {
$sum += $num;
$count++;
}
}
return 0 if $count == 0;
return int( ( $sum / $count ) + 0.5 );
}#!/usr/bin/env python3
"""Divisible Average - Perl Weekly Challenge 398, Task 1."""
from __future__ import annotations
import unittest
def divisible_average(arr: list[int]) -> int:
"""Return the closest integer to the mean of even numbers divisible by 3."""
qualifying = [num for num in arr if num % 6 == 0]
if not qualifying:
return 0
return int(sum(qualifying) / len(qualifying) + 0.5)You are given an array of equal length strings. Write a script to find the difference integer array of each word in the given array and return the one word with a different array.
We compute the difference signature [ord(w[j+1]) - ord(w[j])] for each word and group words by their signature:
1.Time complexity is O(n · L) where L is the word length.
#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Str);
use Test::More;
signature_for string_difference => (
method => 0,
positional => [ ArrayRef [Str] ],
);
sub string_difference ($words) {
my %groups;
for my $word ( @{$words} ) {
my @chars = split //msx, $word;
my $sig = join q{,}, map { ord( $chars[ $_ + 1 ] ) - ord( $chars[$_] ) } 0 .. $#chars - 1;
push @{ $groups{$sig} }, $word;
}
for my $group ( values %groups ) {
return $group->[0] if @{$group} == 1;
}
return q{};
}#!/usr/bin/env python3
"""String Difference - Perl Weekly Challenge 398, Task 2."""
from __future__ import annotations
from collections import defaultdict
import unittest
def string_difference(words: list[str]) -> str:
"""Return the word whose adjacent character difference array is unique."""
groups: dict[tuple[int, ...], list[str]] = defaultdict(list)
for word in words:
sig = tuple(ord(word[i + 1]) - ord(word[i]) for i in range(len(word) - 1))
groups[sig].append(word)
for group in groups.values():
if len(group) == 1:
return group[0]
return ""