The Weekly Challenge 398

Divisible Average & String Difference

Official Challenge • My Solutions on GitHub

Task 1: Divisible Average

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.

Examples

Input: @arr = (18, 5, 7, 11) Output: 18 Input: @arr = (6, 12, 18, 24, 30, 40) Output: 18 Input: @arr = (3, 9, 15, 21, 27) Output: 0 Input: @arr = (6, 12, 14, 20) Output: 9 Input: @arr = (6, 6, 6, 12, 12) Output: 8

Algorithm & Approach

An integer is both even and divisible by 3 if and only if it is divisible by 6:

Runs in O(n) time and O(1) extra space.

Perl Solution

#!/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 );
}

Python Solution

#!/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)

Task 2: String Difference

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.

Examples

Input: @words = ("ab", "bc", "cd", "zy") Output: "zy" Input: @words = ("cba", "fed", "azy") Output: "azy" Input: @words = ("pop", "ada", "beb", "cfc") Output: "pop" Input: @words = ("aaaa", "zzzz", "mmmm", "aaba") Output: "aaba" Input: @words = ("aceg", "bdfh", "cegi", "azbz") Output: "azbz"

Algorithm & Approach

We compute the difference signature [ord(w[j+1]) - ord(w[j])] for each word and group words by their signature:

Time complexity is O(n · L) where L is the word length.

Perl Solution

#!/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{};
}

Python Solution

#!/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 ""