-
-
Save rust-play/0aaa8d492f843109dc49abe8da123b87 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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::iter; | |
fn blend<T>(haystacks: &[&[T]], needles: &[&[T]]) -> Vec<T> | |
where | |
T: PartialEq + Clone + std::fmt::Debug | |
{ | |
if haystacks.is_empty() { return Vec::new() }; | |
// some validity checks for my sanity 😅 | |
assert!(haystacks.len() == needles.len()); | |
assert!(haystacks.iter().all(|hs| hs.len() == haystacks[0].len())); | |
assert!(needles.iter().all(|n| n.len() == needles[0].len())); | |
let mut needles_and_iters: Vec<_> = iter::zip(haystacks, needles).rev().map(|(hs, n)| (*n, hs.chunks(n.len()))).collect(); | |
let mut result = Vec::with_capacity(haystacks[0].len()); | |
loop { | |
let mut found = false; | |
let (_needle, _iter) = &mut needles_and_iters[&needles_and_iters.len()-1].clone(); | |
for (needle, iter) in &mut needles_and_iters { | |
let Some(slice) = iter.next() else { return result }; | |
if slice != *needle && !found { | |
result.extend_from_slice(slice); | |
found = true; | |
// dbg!("The slice is {:?}, the needle is {:?}, I am found: {:?}", &slice, &needle, &found); | |
} | |
} | |
if !found { | |
let Some(slice) = _iter.next() else { return result}; | |
result.extend_from_slice(slice); | |
println!("Not found!") | |
} | |
} | |
} | |
fn main() { | |
let haystacks: &[&[u8]] = &[ | |
&[1,1,2,2,4,4,9,9], | |
&[1,1,8,8,8,8,8,8], | |
&[7,7,7,7,3,3,7,7], | |
]; | |
let needles: &[&[u8]] = &[ | |
&[1, 1], | |
&[8, 8], | |
&[7, 7], | |
]; | |
let result = blend(haystacks, needles); | |
assert!(result == [1,1,2,2,3,3,9,9]); | |
dbg!(blend(haystacks, needles)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment