Skip to content

Instantly share code, notes, and snippets.

@nmrshll
Last active May 19, 2019 18:27
Show Gist options
  • Save nmrshll/04421d6c27831f5ce2b35e3323046f8a to your computer and use it in GitHub Desktop.
Save nmrshll/04421d6c27831f5ce2b35e3323046f8a to your computer and use it in GitHub Desktop.
flatten an array (of i32) in rust
#![allow(non_snake_case)]
/// This rust lib contains one function that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
/// e.g. [[1,2,[3]],4] -> [1,2,3,4].
///
/// # Example usage
///
/// ```
/// use rsflatten::{
/// flatten,
/// Node::{Array as a, I32 as i},
/// };
///
/// let input = a(vec![
/// i(1),
/// a(vec![i(2), i(3), i(4), i(5)]),
/// i(6),
/// a(vec![i(7), i(8), i(9), i(10)]),
/// ]);
/// flatten(&input);
/// ```
///
#[derive(Clone, Debug)]
// Node models the input: an array of {integers OR arbitrarily nested arrays of integers}
pub enum Node {
I32(i32),
Array(Vec<Node>),
}
// flatten flattens a Node. e.g. [[1,2,[3]],4] -> [1,2,3,4].
pub fn flatten(node: &Node) -> Vec<i32> {
match node {
Node::I32(i) => ([*i].to_vec()),
Node::Array(a) => a.iter().fold(vec![], |mut acc, aSubNode| {
for e in flatten(aSubNode) {
acc.push(e)
}
return acc;
}),
}
}
#[cfg(test)]
mod tests {
use super::{
flatten,
Node::{Array as a, I32 as i},
};
#[test]
fn already_flat_array() {
let input = a(vec![i(1), i(2), i(3), i(4)]);
assert_eq!(flatten(&input), vec!(1, 2, 3, 4));
}
#[test]
fn nested_one_level() {
let input = a(vec![
i(1),
a(vec![i(2), i(3), i(4), i(5)]),
i(6),
a(vec![i(7), i(8), i(9), i(10)]),
]);
assert_eq!(flatten(&input), vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
#[test]
fn nested_three_levels() {
let input = a(vec![
i(1),
a(vec![i(2), i(3), i(4), i(5)]),
i(6),
a(vec![
i(7),
i(8),
i(9),
a(vec![i(1), i(2), i(3), a(vec![i(4), i(5), i(6), i(7)])]),
]),
]);
assert_eq!(
flatten(&input),
vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7)
);
}
#[test]
fn empty_array() {
let input = a(vec![]);
assert!(flatten(&input).is_empty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment