The Weekly Challenge 336

Group Partitioning & Score Operations!

Original Challenge Link

Task 1: Equal Group

"GCD of Frequencies: Can You Split Into Equal Chunks?"

Given an array of integers, determine whether it can be partitioned into groups of equal size (at least 2) where all values in each group are identical.

The Strategy: Count frequency of each value. Every frequency must be at least 2 (no singletons). The GCD of all frequencies must also be at least 2, meaning we can divide all values into equal-sized groups.
Perl Implementation
sub _gcd {
    my ( $a, $b ) = @_;
    ( $a, $b ) = ( abs $a, abs $b );
    return $a if $b == 0;
    return _gcd( $b, $a % $b );
}

sub equal_group {
    my (@ints) = @_;
    return 0 if @ints < 2;

    my %freq;
    $freq{$_}++ for @ints;
    my @counts = values %freq;

    return 0 if !all { $_ >= 2 } @counts;

    my $gcd = reduce { _gcd( $a, $b ) } @counts;
    return $gcd >= 2 ? 1 : 0;
}
Python Implementation
from math import gcd
from functools import reduce
from collections import Counter

def equal_group(ints: list[int]) -> bool:
    """Can the array be partitioned into equal-sized identical groups?"""
    if len(ints) < 2:
        return False

    counts = list(Counter(ints).values())
    if any(c < 2 for c in counts):
        return False

    g = reduce(gcd, counts)
    return g >= 2

Task 2: Final Score

"Stack It Up: C, D, Plus, and Numbers!"

Process a sequence of operations on a stack: numbers are pushed, 'C' removes the last, 'D' pushes double the last, '+' pushes the sum of the last two. Return the total sum of all remaining scores.

The Strategy: Simulate the operations using a stack. Numbers get pushed directly. 'C' pops the top. 'D' doubles the top and pushes. '+' sums the top two and pushes. Finally, sum all remaining values.
Perl Implementation
sub final_score {
    my (@entries) = @_;
    my @record;

    for my $entry (@entries) {
        if ( $entry eq 'C' ) {
            pop @record;
        }
        elsif ( $entry eq 'D' ) {
            push @record, 2 * $record[-1];
        }
        elsif ( $entry eq '+' ) {
            push @record, $record[-1] + $record[-2];
        }
        else {
            push @record, 0 + $entry;
        }
    }

    return sum0(@record);
}
Python Implementation
def final_score(entries: list[str]) -> int:
    """Compute final score from C/D/+/number operations."""
    record: list[int] = []

    for entry in entries:
        if entry == "C":
            record.pop()
        elif entry == "D":
            record.append(2 * record[-1])
        elif entry == "+":
            record.append(record[-1] + record[-2])
        else:
            record.append(int(entry))

    return sum(record)