Решение на Matrix 4 от Любен Георгиев

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

Към профила на Любен Георгиев

Резултати

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

Код

use core::ops::Add;
use core::ops::Mul;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
data: [[Cell::<T>; 2]; 2],
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cell<T>(pub T);
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Self::Output {
match self {
Cell::<i32>(x) if x < 0 => Cell::<String>(other.0 + " " + &(-x).to_string()),
Cell::<i32>(x) if x >= 0 => Cell::<String>(x.to_string() + " " + &other.0),
Cell::<i32>(_) => unreachable!(),
}
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Self::Output {
let mut res: String = String::from("");
match self {
Cell::<i32>(x) if x < 0 => {for _ in 0..(-x) { res = res + &other.0 } Cell::<String>(res.chars().rev().collect())},
Cell::<i32>(x) if x > 0 => {for _ in 0..(x) { res = res + &other.0 } Cell::<String>(res)},
Cell::<i32>(_) => Cell::<String>(res),
}
}
}
impl Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, other: Matrix<String>) -> Self::Output {
let nums: Vec<Cell<i32>> = self.by_row();
let strings: Vec<Cell<String>> = other.by_row();
Matrix::<String> {
data: [[nums[0].clone() + strings[0].clone(), nums[1].clone() + strings[1].clone()],
[nums[2].clone() + strings[2].clone(), nums[3].clone() + strings[3].clone()]],
}
}
}
impl Mul<Matrix<String>> for Matrix<i32> {
type Output = String;
fn mul(self, other: Matrix<String>) -> Self::Output {
let nums: Vec<Cell<i32>> = self.by_row();
let strings: Vec<Cell<String>> = other.by_col();
let mut res: String = (nums[0].clone() * strings[0].clone()).0;
for i in 1..4 {
res.push(' ');
res.push_str(&(nums[i].clone() * strings[i].clone()).0);
}
res
}
}
impl<T: Clone> Matrix<T> {
pub fn new(data: &[T; 4]) -> Matrix<T> {
Matrix::<T> {
data: [[Cell::<T>(data[0].clone()), Cell::<T>(data[1].clone())], [Cell::<T>(data[2].clone()), Cell::<T>(data[3].clone())]],
}
}
pub fn by_row(&self) -> Vec<Cell<T>> {
let mut res: Vec<Cell<T>> = Vec::new();
for row in self.data.clone() {
for item in row {
res.push(item);
}
}
res
}
pub fn by_col(&self) -> Vec<Cell<T>> {
let mut res: Vec<Cell<T>> = Vec::new();
let d = self.data.clone();
res.push(d[0][0].clone());
res.push(d[1][0].clone());
res.push(d[0][1].clone());
res.push(d[1][1].clone());
res
}
}

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

Compiling solution v0.1.0 (/tmp/d20220112-2706256-168048b/solution)
    Finished test [unoptimized + debuginfo] target(s) in 7.53s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 15 tests
test solution_test::test_adding_int_and_string_negative ... FAILED
test solution_test::test_adding_int_and_string_positive ... ok
test solution_test::test_adding_int_and_string_unicode ... FAILED
test solution_test::test_adding_int_and_string_zero ... ok
test solution_test::test_adding_matrices_1 ... ok
test solution_test::test_adding_matrices_2 ... FAILED
test solution_test::test_blank_strings ... ok
test solution_test::test_iterating_i32s ... ok
test solution_test::test_iterating_strings ... ok
test solution_test::test_multiplying_int_and_string_negative ... ok
test solution_test::test_multiplying_int_and_string_positive ... ok
test solution_test::test_multiplying_int_and_string_unicode ... ok
test solution_test::test_multiplying_int_and_string_zero ... ok
test solution_test::test_multiplying_matrices_1 ... ok
test solution_test::test_multiplying_matrices_2 ... ok

failures:

---- solution_test::test_adding_int_and_string_negative stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"badger 2"`,
 right: `"regdab 2"`', tests/solution_test.rs:55:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_adding_int_and_string_unicode stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"опа 3"`,
 right: `"апо 3"`', tests/solution_test.rs:64:5

---- solution_test::test_adding_matrices_2 stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[Cell("1 едно"), Cell("0 две"), Cell("  3"), Cell("четири  37")]`,
 right: `[Cell("1 едно"), Cell("0 две"), Cell("  3"), Cell(" иритеч 37")]`', tests/solution_test.rs:125:5


failures:
    solution_test::test_adding_int_and_string_negative
    solution_test::test_adding_int_and_string_unicode
    solution_test::test_adding_matrices_2

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

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

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

Любен качи първо решение на 14.11.2021 14:40 (преди почти 4 години)

Не съм видял в условието, че трябва да е обърнат текста при събиране с отрицателно число. Седемнайсети ред трябва да е така. Cell::(x) if x < 0 => Cell::(other.0.chars().rev().collect::() + " " + &(-x).to_string()),

Не се виждат нещата в коментара, където има скоби за по-малко и по-голямо.

Когато пускаш код, можеш да го обвиеш в backticks (`код`) за да го покажеш без проблеми със специални символи: Cell::<i32>(x) if x < 0 => Cell::<String>(other.0.chars().rev().collect::<String>() + " " + &(-x).to_string()).

Иначе, не ти трябва Cell::<u32>(x), ако компилатора има как да знае какъв е типа на x. Просто Cell(x) ще свърши работа. Донякъде е въпрос на вкус, но би спестило малко писане. А някой, който чете кода, ще се досети какво се връща от неща като type Output = Cell<String>, или даже Cell(... foo.to_string() ...).