Решение на Форматиране на импорти от Милица Тончева

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

Към профила на Милица Тончева

Резултати

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

Код

use std::cmp::Ordering;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Import<'a>(pub &'a [&'a str]);
impl Ord for Import<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.cmp(other.0)
}
}
impl PartialOrd for Import<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Hash for Import<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
for &s in self.0.iter() {
s.hash(state);
}
}
}
pub enum Order {
Original,
Sorted,
}
pub struct Node {
value : String,
children : Vec<Node>,
}
impl Node {
pub fn new(val: String, children: Vec<Node>) -> Self {
Self {
value: val,
children: children,
}
}
pub fn format(&self, result : & mut String, tabs: u16){
let indent = " ".repeat(tabs as usize);
result.push_str(indent.as_str());
result.push_str(self.value.as_str());
if self.children.len() > 0 {
result.push_str("::{\n");
for child in self.children.iter(){
child.format(result, tabs+1);
result.push_str(",\n");
}
result.push_str(indent.as_str());
result.push_str("}");
}
}
}
pub struct Tree{
root : Node,
}
impl Tree{
pub fn new(root: Node) -> Self {
Self{
root,
}
}
pub fn format_tree(&self) -> String {
let mut result= String::new();
self.root.format(&mut result, 0);
result.push_str("\n");
result
}
}
pub fn prepare_imports<'a>(imports: &[Import<'a>], order: Order, correct_imports: &mut Vec<Import<'a>>){
let mut unique = HashSet::new();
let mut temp_imports: Vec<_> = imports.into_iter()
.filter(|&import| unique.insert(import))
.cloned()
.collect();
if let Order::Sorted = order {
temp_imports.sort();
}
correct_imports.extend(temp_imports);
}
pub fn format_flat(imports: &[Import], order: Order) -> Vec<String> {
let mut result : Vec<String>= vec![];
let mut correct_imports = vec![];
prepare_imports(imports, order, &mut correct_imports);
for import in correct_imports {
let joined_import = import.0.join("::");
result.push(joined_import);
}
result
}
pub fn put_element(element: Vec<&str>, root: &mut Node) -> bool{
let head = &element[0];
if !head.eq(&root.value) {
return false;
}
if root.children.len() == 0 || element.len() == 1{
root.children.insert(0, Node::new("self".to_string(), Vec::new()));
if element.len() == 1 {
return true;
}
}
for child in root.children.iter_mut() {
if put_element(element[1..].to_vec(), child) {
return true;
}
}
let new_subtree = create_tree(&element[1..]);
root.children.push(new_subtree.root);
true
}
pub fn create_tree(element: &[&str]) -> Tree{
let mut root = Node::new(String::from(element[0]), Vec::new());
let mut current = &mut root;
for &el in &element[1..] {
let new_child = Node::new(String::from(el), Vec::new());
current.children.push(new_child);
current = current.children.last_mut().unwrap();
}
Tree::new(root)
}
pub fn format_nested(imports: &[Import], order: Order) -> Vec<String> {
let mut result : Vec<String>= vec![];
let mut trees: Vec<Tree> = vec![];
let mut correct_imports = vec![];
prepare_imports(imports, order, &mut correct_imports);
//println!("{:?}", correct_imports);
let mut new_tree_needed:bool;
trees.push(create_tree(&correct_imports[0].0));
for _import in &correct_imports[1..] {
new_tree_needed = true;
for tree in &mut trees {
if put_element(Vec::from(_import.0), &mut tree.root) == true {
new_tree_needed = false;
break;
}
}
if new_tree_needed {
trees.push(create_tree(_import.0));
}
}
for tree in trees {
result.push(tree.format_tree());
}
result
}

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

Compiling solution v0.1.0 (/tmp/d20241203-1739405-15ypbfk/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.30s
     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 ... FAILED
test solution_test::test_nested_only_crate ... ok
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_empty stdout ----
thread 'solution_test::test_nested_empty' panicked at 'index out of bounds: the len is 0 but the index is 0', src/lib.rs:159:29
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_nested_empty

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 коментара)

Милица качи първо решение на 02.12.2024 23:27 (преди 9 месеца)