Решение на Matrix 4 от Димитър Михайлов
Към профила на Димитър Михайлов
Резултати
- 19 точки от тестове
- 0 бонус точки
- 19 точки общо
- 14 успешни тест(а)
- 1 неуспешни тест(а)
Код
use std::{fmt::{Display, Formatter, Result}, ops::{Add, Mul}, process::Output};
#[derive(Debug)]
pub struct Matrix<T: Clone> {
// Каквито данни ви вършат работа
oo: Cell<T>,
o1: Cell<T>,
lo: Cell<T>,
ll: Cell<T>
}
#[derive(Debug, Clone)]
pub struct Cell<T>(pub T);
impl PartialEq<Cell<i32>> for Cell<i32> {
fn eq(&self, other: &Cell<i32>) -> bool {
self.0 == other.0
}
}
impl PartialEq<Cell<String>> for Cell<String> {
fn eq(&self, other: &Cell<String>) -> bool {
self.0 == other.0
}
}
impl PartialEq<Cell<String>> for String {
fn eq(&self, other: &Cell<String>) -> bool {
self.clone() == other.0
}
}
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, rhs: Cell<String>) -> Self::Output {
if self.0 > -1 {
return Cell { 0: self.0.to_string() + " " + rhs.0.to_string().as_str() };
} else {
return Cell { 0: rhs.0.chars().rev().collect::<String>() + " " + (self.0 * -1).to_string().as_str()};
}
}
}
impl Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, rhs: Matrix<String>) -> Self::Output {
return Matrix {
oo: Cell { 0: self.oo.0.to_string() + " " + rhs.oo.0.as_str() },
o1: Cell { 0: self.o1.0.to_string() + " " + rhs.o1.0.as_str() },
lo: Cell { 0: self.lo.0.to_string() + " " + rhs.lo.0.as_str() },
ll: Cell { 0: self.ll.0.to_string() + " " + rhs.ll.0.as_str() },
}
}
}
impl Mul<Matrix<String>> for Matrix<i32> {
type Output = String;
fn mul(self, rhs: Matrix<String>) -> Self::Output {
let mut res = String::new();
let first_by_row = self.by_row();
let second_by_col = rhs.by_col();
res += ((first_by_row[0].clone() * second_by_col[0].clone()).0 + " ").as_str();
res += ((first_by_row[1].clone() * second_by_col[1].clone()).0 + " ").as_str();
res += ((first_by_row[2].clone() * second_by_col[2].clone()).0 + " ").as_str();
res += ((first_by_row[3].clone() * second_by_col[3].clone()).0).as_str();
return res;
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, rhs: Cell<String>) -> Self::Output {
if self.0 > -1 {
let mut res = String::new();
for _ in 0..self.0 {
res += rhs.0.to_string().as_str();
}
return Cell { 0: res };
} else {
let reversed = rhs.0.chars().rev().collect::<String>();
let mut res = String::new();
for _ in 0..self.0 * -1 {
res += reversed.as_str();
}
return Cell { 0: res };
}
}
}
impl Display for Cell<i32> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.0)
}
}
impl Display for Cell<String> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.0)
}
}
impl<T: Clone> Matrix<T> {
/// Данните се очаква да бъдат подадени със статичен масив -- вижте по-долу за примери за
/// конструиране. Какви може да са елементите? Ще тестваме само с два типа: String и i32.
///
/// Очаква се да бъдат подадени по редове, от ляво надясно. Тоест, ако подадем като вход списък
/// с елементи: 1, 2, 3, 4, се очаква конструираната матрица:
///
/// | 1 2 |
/// | 3 4 |
///
/// Забележете, че подаваме като вход някакъв slice -- reference тип. Не очакваме матрицата да
/// държи reference, клонирайте си данните, за да имате ownership.
///
pub fn new(data: &[T; 4]) -> Matrix<T> {
let result = Matrix {
oo: Cell { 0: data[0].clone() },
o1: Cell { 0: data[1].clone() },
lo: Cell { 0: data[2].clone() },
ll: Cell { 0: data[3].clone() },
};
return result;
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
let mut result: Vec<Cell<T>> = Vec::new();
result.push(self.oo.clone());
result.push(self.o1.clone());
result.push(self.lo.clone());
result.push(self.ll.clone());
return result;
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
let mut result: Vec<Cell<T>> = Vec::new();
result.push(self.oo.clone());
result.push(self.lo.clone());
result.push(self.o1.clone());
result.push(self.ll.clone());
return result;
}
}
Лог от изпълнението
Compiling solution v0.1.0 (/tmp/d20220112-2706256-1sf184d/solution) warning: unused import: `process::Output` --> src/lib.rs:1:63 | 1 | use std::{fmt::{Display, Formatter, Result}, ops::{Add, Mul}, process::Output}; | ^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default warning: `solution` (lib) generated 1 warning Finished test [unoptimized + debuginfo] target(s) in 7.40s Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34) running 15 tests test solution_test::test_adding_int_and_string_negative ... ok test solution_test::test_adding_int_and_string_positive ... ok test solution_test::test_adding_int_and_string_unicode ... ok 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_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 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: solution_test::test_adding_matrices_2 test result: FAILED. 14 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test solution_test'