Rustで最も出現頻度の高い文字を探す文字初級編
main.rs
fn main() {
// テキストデータのサンプル
let text = "hello world";
//// HashMapを使って文字の出現頻度をカウント
// char_countは可変。mutを使っている為
let mut char_count = HashMap::new();
// .chars()でcに一個ずつ入れる
for c in text.chars() {
// entry()は指定したキーに対応する値を返す
// or_insert()はキーが存在しない場合に引数で初期化されたエントリを返す
// ここで言うエントリとはキーと値のペアを表す構造体のこと(つーかEntry
// 既に存在する場合には、そのエントリの値を参照する。
let count = char_count.entry(c).or_insert(0);
// *を使うと、ポインタcountが指す値を参照
// 外すと、
// cannot use `+=` on type `&mut {integer}`
// というエラーが出る
*count += 1;
}
// 最も出現頻度の高い文字を探す
let mut max_count = 0;
let mut max_char = ' ';
for (c, count) in &char_count {
if *count > max_count {
max_count = *count;
max_char = *c;
}
}
// 結果を表示
println!("Targetの文字: {}", text);
println!("一番現れた文字: '{}' (回数は{})", max_char, max_count);
}
Rustで最も出現頻度の高い文字を探す文字上級編
main.rs
fn main() {
// 文字列を定義
let s = "hello, world";
// HashMapを作成
let mut counts = HashMap::new();
for c in s.chars() {
// 出現回数をカウント
*counts.entry(c).or_insert(0) += 1;
}
//// 出現回数が最大の文字を検索
// counts.iter()はcountsのキーと値のペア(char, i32)のイテレータを返す
// max_by_key()はクロージャーを引数に取り、そのクロージャーで比較した結果が最大となる要素を返す
let (max_char, max_count) = counts.iter().max_by_key(|&(_, count)| count).unwrap();
// 結果を表示
println!(
"出現頻度が最も高い文字は '{}' で、{} 回出現しました。",
max_char, max_count
);
}
たったこれだけを書くだけでも結構な勉強量になりますな