haar_lib/algo/enum_bit/gray_code.rs
1//! Gray code
2//!
3//! <https://ja.wikipedia.org/wiki/%E3%82%B0%E3%83%AC%E3%82%A4%E3%82%B3%E3%83%BC%E3%83%89>
4
5/// `n`桁のGray codeを昇順に列挙する。
6pub fn gray_code(n: u32) -> impl Iterator<Item = u32> {
7 (0..1 << n).map(|i| i ^ (i >> 1))
8}
9
10#[cfg(test)]
11mod tests {
12 use super::*;
13
14 #[test]
15 fn test() {
16 assert_eq!(
17 gray_code(3).collect::<Vec<_>>(),
18 [0b000, 0b001, 0b011, 0b010, 0b110, 0b111, 0b101, 0b100]
19 );
20 }
21}