5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rust] HashMap は collect で生成できる

Posted at

Rust の HashMap は FromIterator なので, キー (K) と値 (V) のタプル (K, V) を返すイテレータを直接 .collect して生成することができます. これは HashMap の .into_iter の逆操作になっていると言ってもよいです.

具体例として 言語処理100本ノック から「04. 元素記号」を解いてみます.

use std::collections::HashMap;

const ONE_CHAR: &[usize] = &[ 0, 4, 5, 6, 7, 8, 14, 15, 18 ];
const TEXT: &str = "Hi He Lied Because Boron Could Not Oxidize Fluorine. \
New Nations Might Also Sign Peace Security Clause. Arthur King Can";

fn main() {
    let elements: HashMap<&str, usize> = TEXT.split_whitespace()
        .enumerate()
        .map(|(i, text)| {
            if ONE_CHAR.contains(&i) {
                (&text[0..1], i+1)
            } else {
                (&text[0..2], i+1)
            }
        }).collect();
 
    println!("{:?}", elements);
}

{"C": 6, "Be": 4, "P": 15, "F": 9, "Al": 13, "Si": 14, "Ne": 10, "Na": 11, "N": 7, "Mi": 12, "Li": 3, "B": 5, "He": 2, "S": 16, "Ar": 18, "H": 1, "K": 19, "Cl": 17, "O": 8, "Ca": 20} のような出力 (順不同) が得られるはずです. それにしてもこの問題, "Mg" じゃないのとても落ち着かないのですが...

参考文献

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?