Ccmmutty logo
Commutty IT
4 min read

Rust✖️競プロ 覚え書きまとめ

https://cdn.magicode.io/media/notebox/7d351826-a154-4fab-bb27-3325f3bd6ee0.jpeg

はじめに

Rust と AtCoder を勉強するうちに「これよく使うな」と思った処理をまとめていきます!
随時更新していきます!

同じ要素の数を数える(Counter)

use std::collections::HashMap;

let mut counter: HashMap<_type_, usize> = HashMap::new();
for _value_ in _target_ {
    let count = counter.entry(_value_).or_insert(0);
    *count += 1;
}
HashMap から key: K で指定した値を Entry として取り出します。
Entry が空の場合は default: V を挿入します。その後 Entry の値への参照を返します。
rust
// 使用例
// 文字列に含まれるアルファベットがそれぞれいくつあるか数える
use std::collections::HashMap;

let target = "sasakisaku".chars();
let mut counter: HashMap<char, usize> = HashMap::new();
for value in target {
    let count = counter.entry(value).or_insert(0);
    *count += 1;
}

println!("{:?}", counter);

{'k': 2, 'u': 1, 's': 3, 'a': 3, 'i': 1}

アルファベットを列挙する

AtCoder の環境では、'a'..'c' のようにアルファベットの Range を作ることが出来ません。
error[E0277]: the trait bound `char: std::iter::Step` is not satisfied
 --> src/main.rs:2:12
  |
2 |   for c in 'a'..='d' {
  |            ^^^^^^^^^ the trait `std::iter::Step` is not implemented for `char`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<char>`
そのため、以下のようにすると良いです。
rust
// a ~ d を列挙
for c in (b'a'..=b'd').map(char::from) {
  	println!("{}", c);
};

a
b
c
d

同じ値で埋めた Vec を作る

rust
let x = vec![0; 5];
println!("{:?}", x);

[0, 0, 0, 0, 0]

型の最大値・最小値で初期化する

std::T::MIN, std::T::MAX のようにします。
rust
let min_isize = std::isize::MIN;
let max_isize = std::isize::MAX;

println!("isize: {} ~ {}", min_isize, max_isize);

isize: -9223372036854775808 ~ 9223372036854775807

符号なし整数の引き算で桁溢れを回避する

符号なし整数の最小値は当然 00 なので、引き算の結果負の数になるとエラーが発生します。
rust
1u8 - 5u8

Error
this arithmetic operation will overflow
attempt to compute `1_u8 - 5_u8`, which would overflow
this arithmetic operation will overflow
saturating_sub() を使用すると、計算結果は型の最小値・最大値の中に抑えこまれます。つまり、usize 同士の引き算で負になる場合、最小値の 00 になるということです。
rust
println!("{}", 1u8.saturating_sub(5u8));

0

Vec<f64>, Vec<f32> をソートする

Vec<f64>Vec<f32> をソートしようとすると、以下のようにエラーが発生します。
rust
let mut a: Vec<f64> = Vec::from([0.3, 0.1, 0.8]);

a.sort();

Error
the trait bound `f64: Ord` is not satisfied
a.sort();
^^^^ the trait `Ord` is not implemented for `f64`
the trait bound `f64: Ord` is not satisfied
こうしましょう。
rust
a.sort_by(|x, y| x.partial_cmp(y).unwrap());
println!("{:?}", a);

[0.1, 0.3, 0.8]

お手軽素数判定

rust
for n in 500..600 {
    if !(2..n).take_while(|i| i * i <= n).any(|i| n % i == 0) {
      	println!("{}", n);
    }
};

503
509
521
523
541
547
557
563
569
571
577
587
593
599

Discussion

コメントにはログインが必要です。