Created
February 22, 2025 01:15
-
-
Save icub3d/85a992e979dfe1f534db045ecc252631 to your computer and use it in GitHub Desktop.
Leetcode 1980 - Cantor's Diagonal Argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashSet; | |
pub struct Solution; | |
impl Solution { | |
pub fn find_different_binary_string(nums: Vec<String>) -> String { | |
let n = nums.len(); | |
let nums = nums | |
.iter() | |
.map(|s| usize::from_str_radix(s, 2).unwrap()) | |
.collect::<HashSet<usize>>(); | |
for i in 0..=n { | |
if !nums.contains(&i) { | |
return format!("{:0>n$b}", i, n = n); | |
} | |
} | |
unreachable!(); | |
} | |
pub fn cantors_diagonal(nums: Vec<String>) -> String { | |
nums.iter() | |
.enumerate() | |
.map(|(i, n)| n.as_bytes()[i]) | |
.map(|b| if b == b'0' { '1' } else { '0' }) | |
.collect() | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_find_different_binary_string() { | |
assert_eq!( | |
Solution::find_different_binary_string(vec!["01".to_string(), "10".to_string()]), | |
"00" | |
); | |
assert_eq!( | |
Solution::find_different_binary_string(vec!["00".to_string(), "01".to_string()]), | |
"10" | |
); | |
assert_eq!( | |
Solution::find_different_binary_string(vec![ | |
"111".to_string(), | |
"011".to_string(), | |
"001".to_string() | |
]), | |
"000" | |
); | |
} | |
#[test] | |
fn test_cantors_diagonal() { | |
assert_eq!( | |
Solution::cantors_diagonal(vec!["01".to_string(), "10".to_string()]), | |
"11" | |
); | |
assert_eq!( | |
Solution::cantors_diagonal(vec!["00".to_string(), "01".to_string()]), | |
"10" | |
); | |
assert_eq!( | |
Solution::cantors_diagonal(vec![ | |
"111".to_string(), | |
"011".to_string(), | |
"001".to_string() | |
]), | |
"000" | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment