Created
July 13, 2019 05:15
-
-
Save AnaTofuZ/6025197c1b90adbc84509624ca5cbc1a to your computer and use it in GitHub Desktop.
Perl入学式の復習問題
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
#以下のように、 $data に人物名と好きな食べ物がハッシュで与えられています。 食べ物が何回出現したか表示してください。 | |
my %data = ( | |
alice => 'sushi', | |
bob => 'soba', | |
carol => 'sushi', | |
dave => 'sushi', | |
ellen => 'soba', | |
frank => 'udon', | |
); | |
my %food_count = (); | |
map { $food_count{$_}++ } values %data; | |
map { print "food = $_ : cnt= $food_count{$_}\n" } keys %food_count; | |
## 名前順sort | |
print "name sort ----\n"; | |
map { print "food = $_ : cnt= $food_count{$_}\n" } sort keys %food_count; | |
## 出現順sort | |
print "number sort ----\n"; | |
my %count2food = (); | |
for my $food (keys %food_count){ | |
my $cnt = $food_count{$food}; | |
# 同じ回数の食べ物があれば、配列リファレンスに食べ物名をpushする | |
if (exists $count2food{$cnt}){ | |
push(@{$count2food{$cnt}},$food); | |
# 無かったら配列リファレンス生成 | |
} else { | |
$count2food{$cnt} = [$food]; | |
} | |
} | |
for my $cnt (sort {$b <=> $a } keys %count2food){ | |
for my $food (@{$count2food{$cnt}}){ | |
print "food = $food, cnt = $cnt\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment