Решение на Spell Checker от Георги Бонев

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

Към профила на Георги Бонев

Резултати

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

Код

pub const ALPHABET_EN: &'static str = "abcdefghijklmnopqrstuvwxyz";
pub const ALPHABET_BG: &'static str = "абвгдежзийклмнопрстуфхцчшщъьюя";
pub const ALPHABET_EN_B: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub const ALPHABET_BG_B: &'static str = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯ";
pub const AMP: &'static str = "'";
use std::collections::HashMap;
use std::fmt;
fn clean_line(input: &str) -> String {
let mut result = String::from("");
let mut is_letter: bool = false;
let mut is_first_space: bool = true;
for c in input.chars() {
if c == ' ' && is_first_space == true {
is_first_space = false;
}
if c == ' ' && is_first_space == false {
result.push(c);
}
// if c == '-' || c == AMP.chars().nth(0).unwrap() {
if c == '-' || c == '`' {
result.push(c);
}
for letter in ALPHABET_EN.chars() {
if c == letter {
result.push(c);
}
}
for letter in ALPHABET_BG.chars() {
if c == letter {
result.push(c);
}
}
for (i, letter) in ALPHABET_BG_B.chars().enumerate() {
if c == letter {
result.push(ALPHABET_BG.chars().nth(i).unwrap());
}
}
for (i, letter) in ALPHABET_EN_B.chars().enumerate() {
if c == letter {
result.push(ALPHABET_EN.chars().nth(i).unwrap());
}
}
}
result.trim_end();
result
}
pub struct WordCounter {
words:Vec<String>,
counts:Vec<u32>,
}
impl WordCounter {
pub fn new() -> Self {
Self {
words: Vec::new(),
counts: Vec::new(),
}
}
pub fn from_str(input: &str) -> Self {
let s = clean_line(input);
let mut current_word = String::from("");
let mut vec: Vec<String> = Vec::new();
let mut is_first_space = true;
for c in s.chars() {
if c != ' ' {
current_word.push(c);
is_first_space = false;
}
if c == ' ' && is_first_space == false {
vec.push(current_word);
current_word = String::from("");
}
}
Self {words: vec, counts: Vec::new(),}
}
pub fn words(&self) -> Vec<&String> {
let mut vec: Vec<&String> = Vec::new();
for word in &self.words {
vec.push(&word);
}
vec.sort_by(|a, b| a.cmp(&b));
println!("{:?}", vec);
vec
}
/// Връща WordCounter с уникални думи и колко пъти се среща всяка една от тях
pub fn unique_counts(&self) -> Self {
let mut new_counts: Vec<u32> = Vec::new();
let mut new_words: Vec<String> = Vec::new();
let mut i = 0;
let mut j = 0;
while i != self.words.len() {
j = 0;
let mut flag: bool = false;
while j < i {
if self.words[j] == self.words[i] {
flag = true;
}
j = j + 1;
}
if flag == false {
j = 0;
new_words.push(self.words[i].clone());
while j >= i {
if self.words[j] == self.words[i] {
new_counts[i] = new_counts[i] + 1;
}
j = j + 1;
}
}
i = i + 1;
}
Self {
words: new_words,
counts: new_counts,
}
}
pub fn add(&mut self, item: &str) {
unimplemented!()
}
pub fn get(&self, word: &str) -> u32 {
let mut count:u32 = 0;
for current_word in &self.words {
if current_word == word {
count = count + 1;
}
}
count
}
pub fn total_count(&self) -> u32 {
let mut count:u32 = 0;
for word in &self.words {
count = count + 1;
}
println!("{}",count);
count
}
}
// Проблем с връщанат стойност, затова е поставено в коментар
/*impl std::fmt::Display for WordCounter {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
let count:u32 = WordCounter::total_count(self);
let new_vec: Vec<&String> = WordCounter::words(self);
let new_vec_ : Vec<String> = Vec::new();
let mut i = 0;
for word in &new_vec {
new_vec_[i] = word.to_string();
}
let mut new_wordCounter = WordCounter { words: new_vec_, counts: Vec::new(),};
new_wordCounter = WordCounter::unique_counts(&new_wordCounter);
let mut wordCounter_hashMap = HashMap::new();
i = 0;
for word in new_wordCounter.words {
wordCounter_hashMap.insert(word,new_wordCounter.counts[i]);
i = i + 1;
}
let mut count_vec_sort: Vec<_> = wordCounter_hashMap.iter().collect();
count_vec_sort.sort_by(|a, b| b.1.cmp(a.1));
let mut counts_string: Vec<String> = Vec::new();
i = 0;
while i < count_vec_sort.len() {
self.words[i] = count_vec_sort[i].0.to_string();
self.counts[i] = *count_vec_sort[i].1;
let s: String =(*count_vec_sort[i].1) .to_string();
counts_string[i] = s;
i = i + 1;
}
write!(f,"({},{},{:?},{})", "WordCounter, total count: " , count, self.words, "\n" )
}
}*/
fn main() {
}

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

Compiling solution v0.1.0 (/tmp/d20200114-2173579-t0mme6/solution)
warning: unused import: `std::collections::HashMap`
 --> src/lib.rs:7:5
  |
7 | use std::collections::HashMap;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `std::fmt`
 --> src/lib.rs:8:5
  |
8 | use std::fmt;
  |     ^^^^^^^^

warning: unused variable: `is_letter`
  --> src/lib.rs:13:13
   |
13 |     let mut is_letter: bool = false;
   |             ^^^^^^^^^ help: consider prefixing with an underscore: `_is_letter`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: value assigned to `j` is never read
   --> src/lib.rs:109:17
    |
109 |         let mut j = 0;
    |                 ^
    |
    = note: `#[warn(unused_assignments)]` on by default
    = help: maybe it is overwritten before being read?

warning: unused variable: `item`
   --> src/lib.rs:140:27
    |
140 |     pub fn add(&mut self, item: &str) {
    |                           ^^^^ help: consider prefixing with an underscore: `_item`

warning: unused variable: `word`
   --> src/lib.rs:157:13
    |
157 |         for word in &self.words {
    |             ^^^^ help: consider prefixing with an underscore: `_word`

warning: variable does not need to be mutable
  --> src/lib.rs:13:9
   |
13 |     let mut is_letter: bool = false;
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: field is never used: `counts`
  --> src/lib.rs:61:5
   |
61 |     counts:Vec<u32>,
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: function is never used: `main`
   --> src/lib.rs:203:1
    |
203 | fn main() {
    | ^^^^^^^^^

warning: unused return value of `core::str::<impl str>::trim_end` that must be used
  --> src/lib.rs:55:5
   |
55 |     result.trim_end();
   |     ^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: this returns the trimmed string as a new slice, without modifying the original

warning: unused import: `std::collections::HashMap`
 --> src/lib.rs:7:5
  |
7 | use std::collections::HashMap;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `std::fmt`
 --> src/lib.rs:8:5
  |
8 | use std::fmt;
  |     ^^^^^^^^

warning: unused variable: `is_letter`
  --> src/lib.rs:13:13
   |
13 |     let mut is_letter: bool = false;
   |             ^^^^^^^^^ help: consider prefixing with an underscore: `_is_letter`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: value assigned to `j` is never read
   --> src/lib.rs:109:17
    |
109 |         let mut j = 0;
    |                 ^
    |
    = note: `#[warn(unused_assignments)]` on by default
    = help: maybe it is overwritten before being read?

warning: unused variable: `item`
   --> src/lib.rs:140:27
    |
140 |     pub fn add(&mut self, item: &str) {
    |                           ^^^^ help: consider prefixing with an underscore: `_item`

warning: unused variable: `word`
   --> src/lib.rs:157:13
    |
157 |         for word in &self.words {
    |             ^^^^ help: consider prefixing with an underscore: `_word`

warning: variable does not need to be mutable
  --> src/lib.rs:13:9
   |
13 |     let mut is_letter: bool = false;
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: field is never used: `counts`
  --> src/lib.rs:61:5
   |
61 |     counts:Vec<u32>,
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: unused return value of `core::str::<impl str>::trim_end` that must be used
  --> src/lib.rs:55:5
   |
55 |     result.trim_end();
   |     ^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: this returns the trimmed string as a new slice, without modifying the original

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
  --> tests/solution_test.rs:93:25
   |
93 |     let spell_checker = SpellChecker::new("one one two two", "");
   |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
  --> tests/solution_test.rs:98:25
   |
98 |     let spell_checker = SpellChecker::new("three four four four", "");
   |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:103:25
    |
103 |     let spell_checker = SpellChecker::new("one", "");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:109:17
    |
109 |     let edits = SpellChecker::new("", "влпу").edits1("три");
    |                 ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:135:17
    |
135 |     let edits = SpellChecker::new("", "авезийпсц").edits2("три");
    |                 ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:159:25
    |
159 |     let spell_checker = SpellChecker::new("one two three four", "abcdefghijklmnopqrstuvwxyz");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:174:25
    |
174 |     let spell_checker = SpellChecker::new("Любов, любов, варен картоф", "вюф");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:185:25
    |
185 |     let spell_checker = SpellChecker::new("Любов, любов, варен картоф", "вюф");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:196:25
    |
196 |     let spell_checker = SpellChecker::new("Любов, любов, варен картоф", "");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:200:25
    |
200 |     let spell_checker = SpellChecker::new("Любов, любов, варен картоф", "abcdefghijklmnopqrstuvwxyz");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:204:25
    |
204 |     let spell_checker = SpellChecker::new("либофф", "ф");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:212:25
    |
212 |     let spell_checker = SpellChecker::new("boat boot boot boot", "abcdefghijklmnopqrstuvwxyz");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:215:25
    |
215 |     let spell_checker = SpellChecker::new("boat boat boat boot", "abcdefghijklmnopqrstuvwxyz");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0433]: failed to resolve: use of undeclared type or module `SpellChecker`
   --> tests/solution_test.rs:219:25
    |
219 |     let spell_checker = SpellChecker::new("own pawns pawns pawns", "abcdefghijklmnopqrstuvwxyz");
    |                         ^^^^^^^^^^^^ use of undeclared type or module `SpellChecker`

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:60:16
   |
60 |     assert_eq!(clean_line("foo, bar, baz"), String::from("foo bar baz"));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:61:16
   |
61 |     assert_eq!(clean_line("ала,  бала'ница"), String::from("ала  бала'ница"));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:62:16
   |
62 |     assert_eq!(clean_line("-+/"), String::from("-"));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:67:16
   |
67 |     assert_eq!(clean_line(" foo  "), String::from("foo"));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:68:16
   |
68 |     assert_eq!(clean_line("\tfoo"), String::from("foo"));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:69:16
   |
69 |     assert_eq!(clean_line("  "), String::from(""));
   |                ^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `clean_line` in this scope
  --> tests/solution_test.rs:70:16
   |
70 |     assert_eq!(clean_line(""), String::from(""));
   |                ^^^^^^^^^^ not found in this scope

error[E0599]: no method named `to_string` found for type `solution::WordCounter` in the current scope
  --> tests/solution_test.rs:46:24
   |
46 |     assert_eq!(counter.to_string(), "WordCounter, total count: 0\n");
   |                        ^^^^^^^^^ method not found in `solution::WordCounter`
   |
   = note: the method `to_string` exists but the following trait bounds were not satisfied:
           `solution::WordCounter : std::string::ToString`

error[E0599]: no method named `to_string` found for type `solution::WordCounter` in the current scope
  --> tests/solution_test.rs:49:24
   |
49 |     assert_eq!(counter.to_string(), "WordCounter, total count: 1\none: 1\n");
   |                        ^^^^^^^^^ method not found in `solution::WordCounter`
   |
   = note: the method `to_string` exists but the following trait bounds were not satisfied:
           `solution::WordCounter : std::string::ToString`

error[E0599]: no method named `to_string` found for type `solution::WordCounter` in the current scope
  --> tests/solution_test.rs:52:24
   |
52 |     assert_eq!(counter.to_string(), "WordCounter, total count: 3\ntwo: 2\none: 1\n");
   |                        ^^^^^^^^^ method not found in `solution::WordCounter`
   |
   = note: the method `to_string` exists but the following trait bounds were not satisfied:
           `solution::WordCounter : std::string::ToString`

error[E0599]: no method named `to_string` found for type `solution::WordCounter` in the current scope
  --> tests/solution_test.rs:55:24
   |
55 |     assert_eq!(counter.to_string(), "WordCounter, total count: 6\nthree: 3\ntwo: 2\none: 1\n");
   |                        ^^^^^^^^^ method not found in `solution::WordCounter`
   |
   = note: the method `to_string` exists but the following trait bounds were not satisfied:
           `solution::WordCounter : std::string::ToString`

error: aborting due to 25 previous errors

Some errors have detailed explanations: E0425, E0433, E0599.
For more information about an error, try `rustc --explain E0425`.
error: could not compile `solution`.

To learn more, run the command again with --verbose.

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

Георги качи първо решение на 14.01.2020 11:48 (преди над 5 години)

Без да имаш SpellChecker структура, няма как да ти се компилира решението с тестовете. Дали сме ви шаблон, за да можете поне да копирате шаблона и да се компилира, и да го запълните с каквото ви трябва. Можеше да оставиш методи като unimplemented!() и щяха да гърмят в тестовете, но поне щеше да изкараш някакви точки вероятно. Не знам защо си решил просто да изтриеш/закоментираш нещата. Това със сигурност няма да се компилира дори с базовия тест.

Здравейте! Не съобразих това със структурата на SpellChecker. Бях притиснат от времето и исках да кача навреме това, което съм успял да напиша, в случай, че бъде погледнато и оценено по някакъв начин. Поздрави!