多数の国の行を含むファイルを反復処理し、最も多く発生する国を印刷するための最良のアルゴリズム/アプローチは何ですか?
各行は文字列であり、各行には国名のみが含まれています。
10億の異なる国が存在する可能性があると仮定します。(国は悪い例です)
United States
Iran
India
United States
China
Iran
....
....
Canada //1 billionth line
# Count the unique elements.
my %hash;
while(<>) {
chomp;
$hash{$_}++;
}
# Find the key with the largest value.
sub largest_value {
my $hash = shift;
my ($big_key, $big_val) = each %$hash;
while (my ($key, $val) = each %$hash) {
if ($val > $big_val) {
$big_key = $key;
$big_val = $val;
}
}
return $big_key;
}
print largest_value(\%hash);
整数のハッシュを使用できます。行数は多いですが、国名は数に限りがあるため、ファイルサイズはそれほど重要ではありません。
use strict;
use warnings;
my %hash;
while(<>) {
chomp;
$hash{$_}++;
}
my @sorted = sort { $hash{$b} <=> $hash{$b} } keys %hash;
print "$sorted[0]: $hash{$sorted[0]}\n";
my $big_count = 0;
my @big_keys;
my %counts;
while (<>) {
chomp;
my $count = ++$counts{$_};
if ($counts == $big_count) {
push @big_keys, $_;
}
elsif ($count > $big_count) {
$big_count = $count;
@big_keys = $_;
}
}
print(join(', ', @big_keys), "\n");
ハッシュテーブルを作成します。keyは国名、valueは出現回数です。