Skip to content

Commit 5e2d1e2

Browse files
authored
Implement n bits gray code (#787)
feat: add `n_bits_gray_code.rs`
1 parent 84c4665 commit 5e2d1e2

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/bit_manipulation/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
mod counting_bits;
22
mod highest_set_bit;
3+
mod n_bits_gray_code;
34
mod sum_of_two_integers;
45

56
pub use counting_bits::count_set_bits;
67
pub use highest_set_bit::find_highest_set_bit;
8+
pub use n_bits_gray_code::generate_gray_code;
79
pub use sum_of_two_integers::add_two_integers;
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/// Custom error type for Gray code generation.
2+
#[derive(Debug, PartialEq)]
3+
pub enum GrayCodeError {
4+
ZeroBitCount,
5+
}
6+
7+
/// Generates an n-bit Gray code sequence using the direct Gray code formula.
8+
///
9+
/// # Arguments
10+
///
11+
/// * `n` - The number of bits for the Gray code.
12+
///
13+
/// # Returns
14+
///
15+
/// A vector of Gray code sequences as strings.
16+
pub fn generate_gray_code(n: usize) -> Result<Vec<String>, GrayCodeError> {
17+
if n == 0 {
18+
return Err(GrayCodeError::ZeroBitCount);
19+
}
20+
21+
let num_codes = 1 << n;
22+
let mut result = Vec::with_capacity(num_codes);
23+
24+
for i in 0..num_codes {
25+
let gray = i ^ (i >> 1);
26+
let gray_code = (0..n)
27+
.rev()
28+
.map(|bit| if gray & (1 << bit) != 0 { '1' } else { '0' })
29+
.collect::<String>();
30+
result.push(gray_code);
31+
}
32+
33+
Ok(result)
34+
}
35+
36+
#[cfg(test)]
37+
mod tests {
38+
use super::*;
39+
40+
macro_rules! gray_code_tests {
41+
($($name:ident: $test_case:expr,)*) => {
42+
$(
43+
#[test]
44+
fn $name() {
45+
let (input, expected) = $test_case;
46+
assert_eq!(generate_gray_code(input), expected);
47+
}
48+
)*
49+
};
50+
}
51+
52+
gray_code_tests! {
53+
zero_bit_count: (0, Err(GrayCodeError::ZeroBitCount)),
54+
gray_code_1_bit: (1, Ok(vec![
55+
"0".to_string(),
56+
"1".to_string(),
57+
])),
58+
gray_code_2_bit: (2, Ok(vec![
59+
"00".to_string(),
60+
"01".to_string(),
61+
"11".to_string(),
62+
"10".to_string(),
63+
])),
64+
gray_code_3_bit: (3, Ok(vec![
65+
"000".to_string(),
66+
"001".to_string(),
67+
"011".to_string(),
68+
"010".to_string(),
69+
"110".to_string(),
70+
"111".to_string(),
71+
"101".to_string(),
72+
"100".to_string(),
73+
])),
74+
}
75+
}

0 commit comments

Comments
 (0)