Task 1: Counter Integers
"The Integer Filter: Finding Distinct Numbers!"
Extract all unique integers from a string containing lowercase letters and digits by replacing non-digit characters with spaces.
The Strategy: Both solutions follow the same logic: replace all non-digit characters (regex
\D or [^0-9]) with spaces. Split the resulting string by whitespace to get individual number chunks. Maintain a "seen" set/hash to filter out duplicates while preserving the original order of first appearance.
Perl Implementation
sub counter_integers {
my ($str) = @_;
my $digits_as_spaces = $str =~ s/\D+/ /gr;
my %seen;
my @uniq;
for my $chunk (split /\s+/, $digits_as_spaces) {
next unless length $chunk;
next if $seen{$chunk}++;
push @uniq, 0 + $chunk;
}
return \@uniq;
}
Python Implementation
def counter_integers(text: str) -> list[int]:
digits_as_spaces = "".join(ch if ch.isdigit() else " " for ch in text)
seen = set()
result = []
for chunk in digits_as_spaces.split():
if chunk not in seen:
seen.add(chunk)
result.append(int(chunk))
return result