Решение на Matrix 4 от Павел Цанов

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

Към профила на Павел Цанов

Резултати

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

Код

use std::ops::Add;
use std::ops::Mul;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
// Каквито данни ви вършат работа
cells: Vec<Cell<T>>
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cell<T>(pub T);
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 mut vec = Vec::new();
for i in data.clone() {
vec.push(Cell(i))
}
Matrix { cells: vec }
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
self.cells.clone()
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
let mut col_vec = Vec::new();
col_vec.push(self.cells[0].clone());
col_vec.push(self.cells[2].clone());
col_vec.push(self.cells[1].clone());
col_vec.push(self.cells[3].clone());
col_vec
}
}
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Cell<String> {
if self.0 >= 0 {
Cell {
0: self.0.to_string() + " " + &other.0
}
} else {
Cell {
0: other.0.chars().rev().collect::<String>() + " " + &(self.0 * (-1)).to_string()
}
}
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Cell<String> {
let mut result: String = other.0.clone();
if self.0 == 0 {
Cell {
0: "".to_string()
}
} else {
let mut number = self.0;
if number < 0 {
number = number * -1;
result = result.chars().rev().collect::<String>();
}
for _ in 1..number{
if self.0 < 0 {
result += &other.0.clone().chars().rev().collect::<String>();
}
else {
result += &other.0.clone();
}
}
Cell {
0: result
}
}
}
}
impl Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, other: Matrix<String>) -> Matrix<String> {
let mut vec = Vec::new();
for i in 0..4{
vec.push(self.by_row()[i].clone() + other.by_row()[i].clone());
}
Matrix{ cells: vec}
}
}
impl Mul<Matrix<String>> for Matrix<i32> {
type Output = String;
fn mul(self, other: Matrix<String>) -> String {
let mut str = "".to_string();
for i in 0..4{
str += &(self.by_col()[i].clone() * other.by_col()[i].clone()).0;
if i != 3 {
str += " ";
}
}
str
}
}

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

Compiling solution v0.1.0 (/tmp/d20220112-2706256-se13cm/solution)
    Finished test [unoptimized + debuginfo] target(s) in 8.71s
     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 ... ok
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 ... FAILED
test solution_test::test_multiplying_matrices_2 ... FAILED

failures:

---- solution_test::test_multiplying_matrices_1 stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"one threethreethree twotwo you get it"`,
 right: `"one threethree twotwotwo you get it"`', tests/solution_test.rs:139:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_multiplying_matrices_2 stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"едно       иритеч иритеч"`,
 right: `"едно  евдевдевд  иритеч иритеч"`', tests/solution_test.rs:153:5


failures:
    solution_test::test_multiplying_matrices_1
    solution_test::test_multiplying_matrices_2

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

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

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

Павел качи първо решение на 18.11.2021 07:59 (преди почти 4 години)