Решение на Matrix 4 от Марио Николов
Резултати
- 20 точки от тестове
- 0 бонус точки
- 20 точки общо
- 15 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::ops::Add;
use std::ops::Mul;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
first: Cell<T>,
second: Cell<T>,
third: Cell<T>,
fourth: 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> {
Matrix{
first: Cell(data[0].clone()),
second: Cell(data[1].clone()),
third: Cell(data[2].clone()),
fourth: Cell(data[3].clone())
}
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
vec![
self.first.clone(),
self.second.clone(),
self.third.clone(),
self.fourth.clone()
]
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
vec![
self.first.clone(),
self.third.clone(),
self.second.clone(),
self.fourth.clone()
]
}
}
impl Add<Cell<String>> for Cell<i32>{
type Output=Cell<String>;
fn add(self, other:Cell<String>) -> Self::Output{
let firstr=if self.0 < 0 {
format!("{} {}", other.0.chars().rev().collect::<String>(), (self.0)*-1)
}
else {
format!("{} {}", self.0, other.0)
};
Cell(String::from(firstr.clone()))
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output=Cell<String>;
fn mul(self,other:Cell<String>) -> Self::Output{
let mut firstr=String::from("");
if self.0 < 0 {
for _i in 0..(self.0*-1) {
firstr += &other.0.chars().rev().collect::<String>();
}
}
else {
for _i in 0..(self.0) {
firstr += &other.0;
}
}
Cell(String::from(firstr.clone()))
}
}
impl Add<Matrix<String>> for Matrix<i32>{
type Output=Matrix<String>;
fn add(self,other:Matrix<String>) -> Self::Output{
Matrix{
first: self.first + other.first,
second: self.second + other.second,
third: self.third + other.third,
fourth: self.fourth + other.fourth
}
}
}
impl Mul<Matrix<String>> for Matrix<i32>{
type Output=String;
fn mul(self,other:Matrix<String>) -> Self::Output{
let firstr=self.first*other.first;
let secondr=self.second*other.third;
let thirdr=self.third*other.second;
let fourthr=self.fourth*other.fourth;
format!("{} {} {} {}", firstr.0, secondr.0, thirdr.0, fourthr.0)
}
}
Лог от изпълнението
Compiling solution v0.1.0 (/tmp/d20220112-2706256-yfuf2i/solution) Finished test [unoptimized + debuginfo] target(s) in 7.35s 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.00s