Решение на Matrix 4 от Николай Шиваров

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

Към профила на Николай Шиваров

Резултати

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

Код

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

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

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

test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s

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

Николай качи първо решение на 15.11.2021 17:47 (преди почти 4 години)