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

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

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

Резултати

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

Код

use std::cmp::Ordering;
pub struct Tree { root: Node }
impl Tree {
fn new(value: &str) -> Tree {
Tree { root: Node::new(value) }
}
fn sink(&mut self, import: &Import) {
if import.0.is_empty() {
return;
}
let first_imp = import.0[0];
if let Some(node) = self.root.children.iter_mut().find(|node| node.value == first_imp) {
node.sink(&import.0[1..]);
} else {
let new_child = self.root.add_child(first_imp);
new_child.sink(&import.0[1..]);
}
}
fn to_strings(mut self, order: Order) -> Vec<String> {
let mut result = Vec::<String>::new();
if let Order::Sorted = order {
self.root.children.sort();
}
for sutbree in self.root.children {
let mut result_str = String::new();
sutbree.to_string(0, &mut result_str, &order);
result.push(result_str);
}
result
}
fn check_for_self(&mut self, import: &Import) {
for subtree in self.root.children.iter_mut() {
subtree.check_for_self(&import.0[1..]);
}
}
}
pub struct Node {pub value: String, pub children: Vec<Node>}
impl Ord for Node {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.value == "self" {
Ordering::Less
} else if other.value == "self" {
Ordering::Greater
} else {
self.value.cmp(&other.value)
}
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for Node {}
impl Node {
fn new(val: &str) -> Node {
Node { value: val.to_string(), children: Vec::new()}
}
fn add_child(&mut self, val: &str) -> &mut Node {
if val == "self" {
self.children.insert(0, Node::new(val));
self.children.first_mut().unwrap()
} else {
self.children.push(Node::new(val));
self.children.last_mut().unwrap()
}
}
fn find_by_value(&mut self, val: &str) -> Option<&mut Node> {
self.children.iter_mut().find(|node| node.value == val)
}
fn sink(&mut self, imports: &[&str]) {
if imports.is_empty() {
return;
}
let first_imp = imports[0];
if let Some(node) = self.children.iter_mut().find(|node| node.value == first_imp) {
node.sink(&imports[1..]);
} else {
let new_child = self.add_child(first_imp);
new_child.sink(&imports[1..]);
}
}
fn to_string(mut self, spaces: usize, result: &mut String, order: &Order) {
if self.children.is_empty() {
result.push_str(&format!("{}{},\n", " ".repeat(spaces), self.value));
return;
}
if let Order::Sorted = order {
self.children.sort();
}
result.push_str(&format!("{}{}::{{\n", " ".repeat(spaces), self.value));
for child in self.children {
child.to_string(spaces + 4, result, order);
}
if spaces > 0 {
result.push_str(&format!("{}}},\n", " ".repeat(spaces)));
} else {
result.push_str(&format!("{}}}\n", " ".repeat(spaces)));
}
}
fn check_for_self(&mut self, imports: &[&str]) {
if imports.len() == 0 && self.children.len() > 0 {
self.add_child("self");
} else if imports.len() > 0{
match self.find_by_value(imports[0]) {
Some(node) => node.check_for_self(&imports[1..]),
None => return,
}
}
}
}
pub struct Import<'a>(pub &'a [&'a str]);
pub enum Order {
Original,
Sorted,
}
impl Order {
fn normalize(self, input: &mut Vec<String>){
match self {
Order::Original => {},
Order::Sorted => input.sort()
}
}
}
pub fn format_flat(imports: &[Import], order: Order) -> Vec<String> {
let mut formated_imports = Vec::new();
for import in imports {
let formatted = import.0.join("::");
if !formated_imports.contains(&formatted) {
formated_imports.push(formatted);
}
}
order.normalize(&mut formated_imports);
formated_imports
}
pub fn format_nested(imports: &[Import], order: Order) -> Vec<String> {
let mut tree = Tree::new("_ROOT");
for import in imports {
tree.sink(import);
}
for import in imports {
tree.check_for_self(import);
}
tree.to_strings(order)
}

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

Compiling solution v0.1.0 (/tmp/d20241203-1739405-i9s151/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.83s
     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 ... ok
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_duplicates ... ok
test solution_test::test_nested_sorted_multi_crate ... ok
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


failures:
    solution_test::test_nested_only_crate

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

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

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

Александър качи първо решение на 03.12.2024 01:27 (преди 9 месеца)