|
| 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