Решение на Matrix 4 от Виктор Терзиев

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

Към профила на Виктор Терзиев

Резултати

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

Код

use std::convert::TryInto;
use std::ops::Add;
use std::ops::Mul;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
content: [ [Cell<T>; 2]; 2]
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cell<T>(pub T);
impl<T: Clone> Matrix<T> {
pub fn new(data: &[T; 4]) -> Matrix<T> {
let content = [ [Cell(data[0].clone()),Cell(data[1].clone())], [Cell(data[2].clone()), Cell(data[3].clone())] ];
Matrix {
content: content
}
}
pub fn by_row(&self) -> Vec<Cell<T>> {
vec!(self.content[0][0].clone(), self.content[0][1].clone(), self.content[1][0].clone(), self.content[1][1].clone())
}
pub fn by_col(&self) -> Vec<Cell<T>> {
vec![self.content[0][0].clone(), self.content[1][0].clone(), self.content[0][1].clone(), self.content[1][1].clone()]
}
}
impl Add<Cell<String> > for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Self::Output {
if self.0 >= 0 {
let mut prefix = self.0.to_string();
prefix.push_str(" ");
prefix.push_str(&other.0);
Cell(prefix)
} else {
let mut prefix = other.0;
prefix = prefix.chars().rev().collect();
prefix.push_str(" ");
prefix.push_str(&(-self.0).to_string());
Cell(prefix)
}
}
}
impl Mul<Cell<String> > for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Self::Output {
if self.0 == 0 {
Cell("".to_string())
} else if self.0 > 0 {
Cell(other.0.repeat(self.0.try_into().unwrap()))
} else {
let prefix: String = other.0.chars().rev().collect();
Cell(prefix.repeat((-self.0).try_into().unwrap()))
}
}
}
impl Add<Matrix<String> > for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, other: Matrix<String>) -> Self::Output {
let l = self.by_row();
let r = other.by_row();
let data = [
(l[0].clone() + r[0].clone()).0,
(l[1].clone() + r[1].clone()).0,
(l[2].clone() + r[2].clone()).0,
(l[3].clone() + r[3].clone()).0];
Matrix::new(&data)
}
}
impl Mul<Matrix<String> > for Matrix<i32> {
type Output = String;
fn mul(self, other: Matrix<String>) -> Self::Output {
let l = self.by_row();
let r = other.by_col();
let data = [
(l[0].clone() * r[0].clone()).0,
(l[1].clone() * r[1].clone()).0,
(l[2].clone() * r[2].clone()).0,
(l[3].clone() * r[3].clone()).0];
let mut result = data[0].clone();
result.push( ' ');
result.push_str(&data[1]);
result.push( ' ');
result.push_str(&data[2]);
result.push( ' ');
result.push_str(&data[3]);
result
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn t() {
assert_eq!((Cell(1) + Cell(String::from("ABC"))).0, String::from("1 ABC"));
assert_eq!((Cell(0) + Cell(String::from("ABC"))).0, String::from("0 ABC"));
assert_eq!((Cell(2) + Cell(String::from("ABC"))).0, String::from("2 ABC"));
assert_eq!((Cell(-1) + Cell(String::from("ABC"))).0, String::from("CBA 1"));
assert_eq!((Cell(-2) + Cell(String::from("ABC"))).0, String::from("CBA 2"));
assert_eq!((Cell(2) + Cell(String::from("😀"))).0, String::from("2 😀"));
assert_eq!((Cell(-2) + Cell(String::from("😀"))).0, String::from("😀 2"));
assert_eq!((Cell(1) * Cell(String::from("ABC"))).0, String::from("ABC"));
assert_eq!((Cell(0) * Cell(String::from("ABC"))).0, String::from(""));
assert_eq!((Cell(2) * Cell(String::from("ABC"))).0, String::from("ABCABC"));
assert_eq!((Cell(-1) * Cell(String::from("ABC"))).0, String::from("CBA"));
assert_eq!((Cell(-2) * Cell(String::from("ABC"))).0, String::from("CBACBA"));
assert_eq!((Cell(2) * Cell(String::from("😀"))).0, String::from("😀😀"));
assert_eq!((Cell(-2) * Cell(String::from("😀"))).0, String::from("😀😀"));
let matrix1 = Matrix::new(&[1, 0, -1, 2]);
let matrix2 = Matrix::new(&[
String::from("one"), String::from("two"),
String::from("three"), String::from("four")
]);
assert_eq!(
(matrix1 + matrix2).by_row(),
vec![Cell("1 one".to_string()), Cell("0 two".to_string()), Cell("eerht 1".to_string()), Cell("2 four".to_string())]
);
let matrix1 = Matrix::new(&[2, 0, -1, -2]);
let matrix2 = Matrix::new(&[
String::from("one"), String::from("two"),
String::from("three"), String::from("four")
]);
assert_eq!(matrix1 * matrix2, String::from("oneone owt ruofruof"));
}
}

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

Compiling solution v0.1.0 (/tmp/d20220112-2706256-1nnkipw/solution)
    Finished test [unoptimized + debuginfo] target(s) in 7.42s
     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 версия и 1 коментар)

Виктор качи първо решение на 13.11.2021 21:19 (преди почти 4 години)

Обилен комплект от тестове за Cell операции, включително unicode 👍. От друга страна, можеше да добавиш две emoji-та, за да се тества, че работи обръщането :). Матриците също са тествани само с латиница. Може да се направи аргумента, че използват Cell операции, но това донякъде е имплементационен детайл и е добра идея да имаш тестове за unicode и за тях.