Решение на Форматиране на импорти от Александър Терезов

Обратно към всички решения

Към профила на Александър Терезов

Резултати

  • 17 точки от тестове
  • 0 бонус точки
  • 17 точки общо
  • 17 успешни тест(а)
  • 3 неуспешни тест(а)

Код

pub struct Import<'a>(pub &'a [&'a str]);
pub enum Order {
Original,
Sorted,
}
pub fn format_flat(imports: &[Import], order: Order) -> Vec<String> {
let mut paths: Vec<String> = imports.iter().map(|import| import.0.join("::")).collect();
let mut unique_paths = Vec::new();
if let Order::Sorted = order {
//Dedup with sort
paths.sort();
paths.dedup();
unique_paths = paths;
} else {
//Dedup without sort
for path in paths.into_iter() {
if !unique_paths.contains(&path) {
unique_paths.push(path);
}
}
}
unique_paths
}
struct Tree {
root: Node,
}
struct Node {
value: String,
children: Vec<Node>,
}
impl Tree {
fn new() -> Self {
Self {
root: Node {
value: String::from("root"),
children: Vec::new(),
},
}
}
fn add_import(&mut self, import: &Import) {
let mut current_node = &mut self.root;
//Push the parts into the tree
for part in import.0 {
let mut found = false;
for i in 0..current_node.children.len() {
if current_node.children[i].value == *part {
current_node = &mut current_node.children[i];
found = true;
break;
}
}
if !found {
current_node.children.push(Node {
value: part.to_string(),
children: Vec::new(),
});
current_node = current_node.children.last_mut().unwrap();
}
}
//Insert the "self" at the top
current_node.children.insert(
0,
Node {
value: "self".to_string(),
children: Vec::new(),
},
);
}
fn add_imports(&mut self, imports: &[Import]) {
for import in imports {
self.add_import(import);
}
}
fn sort_tree(&mut self) {
self.root.sort();
}
fn to_formatted_vec(&self) -> Vec<String> {
let mut result = Vec::new();
for child in &self.root.children {
let mut string_to_push = String::new();
child.format(&mut string_to_push, 0);
result.push(string_to_push);
}
result
}
}
impl Node {
fn format(&self, result: &mut String, level: usize) {
if self.children.is_empty() {
result.push_str(&" ".repeat(level));
result.push_str(&format!("{},\n", self.value));
} else {
if self.children.len() == 1 && self.children[0].value == "self" {
result.push_str(&" ".repeat(level));
result.push_str(&format!("{},\n", self.value));
} else {
result.push_str(&" ".repeat(level));
result.push_str(&format!("{}::{{\n", self.value));
for child in &self.children {
child.format(result, level + 1);
}
result.push_str(&" ".repeat(level));
if level != 0 {
result.push_str("},\n");
} else {
result.push_str("}\n");
}
}
}
}
fn sort(&mut self) {
for child in &mut self.children {
child.sort();
}
self.children.sort_by(|a, b| {
if a.value == "self" && b.value != "self" {
std::cmp::Ordering::Less
} else if a.value != "self" && b.value == "self" {
std::cmp::Ordering::Greater
} else {
a.value.cmp(&b.value)
}
});
}
}
pub fn format_nested(imports: &[Import], order: Order) -> Vec<String> {
let mut tree = Tree::new();
tree.add_imports(imports);
if let Order::Sorted = order {
tree.sort_tree();
}
let formatted = tree.to_formatted_vec();
formatted
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20241203-1739405-1g18yyv/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.12s
     Running tests/solution_test.rs (target/debug/deps/solution_test-1428e1090729d165)

running 20 tests
test solution_test::test_flat_empty ... ok
test solution_test::test_flat_multi_crate ... ok
test solution_test::test_flat_original ... ok
test solution_test::test_flat_original_duplicates ... ok
test solution_test::test_flat_sorted ... ok
test solution_test::test_flat_sorted_duplicates ... ok
test solution_test::test_nested_basic ... ok
test solution_test::test_nested_deep ... ok
test solution_test::test_nested_empty ... ok
test solution_test::test_nested_only_crate ... FAILED
test solution_test::test_nested_original ... ok
test solution_test::test_nested_original_2 ... ok
test solution_test::test_nested_original_duplicates ... FAILED
test solution_test::test_nested_original_multi_crate ... ok
test solution_test::test_nested_original_self ... ok
test solution_test::test_nested_sorted ... ok
test solution_test::test_nested_sorted_2 ... ok
test solution_test::test_nested_sorted_multi_crate ... ok
test solution_test::test_nested_sorted_duplicates ... FAILED
test solution_test::test_nested_sorted_self ... ok

failures:

---- solution_test::test_nested_only_crate stdout ----
thread 'solution_test::test_nested_only_crate' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate,\n"]`,
 right: `["my_crate\n"]`', tests/solution_test.rs:132:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_nested_original_duplicates stdout ----
thread 'solution_test::test_nested_original_duplicates' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate::{\n    c::{\n        self,\n        self,\n    },\n    b::{\n        B2::{\n            self,\n            self,\n        },\n        B1,\n    },\n    a,\n}\n"]`,
 right: `["my_crate::{\n    c,\n    b::{\n        B2,\n        B1,\n    },\n    a,\n}\n"]`', tests/solution_test.rs:283:5

---- solution_test::test_nested_sorted_duplicates stdout ----
thread 'solution_test::test_nested_sorted_duplicates' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate::{\n    a,\n    b::{\n        B1,\n        B2::{\n            self,\n            self,\n        },\n    },\n    c::{\n        self,\n        self,\n    },\n}\n"]`,
 right: `["my_crate::{\n    a,\n    b::{\n        B1,\n        B2,\n    },\n    c,\n}\n"]`', tests/solution_test.rs:309:5


failures:
    solution_test::test_nested_only_crate
    solution_test::test_nested_original_duplicates
    solution_test::test_nested_sorted_duplicates

test result: FAILED. 17 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--test solution_test`

История (1 версия и 0 коментара)

Александър качи първо решение на 01.12.2024 00:45 (преди 10 месеца)