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