Решение на Matrix 4 от Елизабет Колева

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

Към профила на Елизабет Колева

Резултати

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

Код

#[derive(Debug)]
pub struct Matrix<T: Clone> {
data: Vec<Cell<T>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cell<T>(pub T);
impl<T: Clone> Matrix<T> {
pub fn new(input_data: &[T; 4]) -> Matrix<T> {
let mut data: Vec<Cell<T>> = vec![];
for elem in input_data {
data.push(Cell(elem.clone()));
}
Matrix { data }
}
pub fn by_row(&self) -> Vec<Cell<T>> {
self.data.clone()
}
pub fn by_col(&self) -> Vec<Cell<T>> {
let mut transponse_matrix = self.by_row();
transponse_matrix.swap(1, 2);
transponse_matrix
}
}
impl std::ops::Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, rhs: Cell<String>) -> Self::Output {
let mut result: String;
if self.0 >= 0 {
result = self.0.to_string();
result.push_str(" ");
result.push_str(&rhs.0);
} else {
result = rhs.0.chars().rev().collect();
result.push_str(" ");
result.push_str(&(-self.0).to_string());
}
Cell(result)
}
}
impl std::ops::Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, rhs: Cell<String>) -> Self::Output {
let mut result: String = String::from("");
let (iter_count, help_str) = if self.0 >= 0 {
(self.0, rhs.0)
} else {
(-self.0, rhs.0.chars().rev().collect::<String>())
};
for _ in 0..iter_count {
result.push_str(&help_str);
}
Cell(result)
}
}
impl std::ops::Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, rhs: Matrix<String>) -> Self::Output {
let mut data: Vec<Cell<String>> = vec![];
let mut iter_num = self.by_row().into_iter();
let mut iter_str = rhs.by_row().into_iter();
while let (Some(iter_num_elem), Some(iter_str_elem)) = (iter_num.next(), iter_str.next()) {
data.push(iter_num_elem + iter_str_elem);
}
Matrix { data }
}
}
impl std::ops::Mul<Matrix<String>> for Matrix<i32> {
type Output = String;
fn mul(self, rhs: Matrix<String>) -> Self::Output {
let mut data: String = String::from("");
let mut iter_num = self.by_row().into_iter();
let mut iter_str = rhs.by_col().into_iter();
let mut flag: bool = true;
while let (Some(iter_num_elem), Some(iter_str_elem)) = (iter_num.next(), iter_str.next()) {
let str = iter_num_elem * iter_str_elem;
if flag {
flag = false;
}
else {
data.push_str(" ");
}
data.push_str(&str.0);
}
data
}
}
#[cfg(test)]
mod tests {
use crate::{Cell, Matrix};
#[test]
fn test_matrix_by_row() {
let u_matrix = Matrix::new(&[1, 2, 3, 4]);
assert_eq!(u_matrix.by_row(), vec![Cell(1), Cell(2), Cell(3), Cell(4)]);
}
#[test]
fn test_matrix_by_col() {
let u_matrix = Matrix::new(&[1, 2, 3, 4]);
assert_eq!(u_matrix.by_col(), vec![Cell(1), Cell(3), Cell(2), Cell(4)]);
}
#[test]
fn test_cell_addition_positive() {
let cell_number: Cell<i32> = Cell(22);
let cell_string: Cell<String> = Cell(String::from("Lizi Blizi"));
assert_eq!(cell_number + cell_string, Cell(String::from("22 Lizi Blizi")));
}
#[test]
fn test_cell_additon_negative() {
let cell_number: Cell<i32> = Cell(-111);
let cell_string: Cell<String> = Cell(String::from("neG ,ereht olleH"));
assert_eq!(cell_number + cell_string, Cell(String::from("Hello there, Gen 111")));
}
#[test]
fn test_cell_additon_negative_zero() {
let cell_number: Cell<i32> = Cell(-0);
let cell_string: Cell<String> = Cell(String::from("neG ,ereht olleH"));
assert_eq!(cell_number + cell_string, Cell(String::from("0 neG ,ereht olleH")));
}
#[test]
fn test_cell_multiply_positive() {
let cell_number: Cell<i32> = Cell(4);
let cell_string: Cell<String> = Cell(String::from("Meow x3"));
assert_eq!(cell_number * cell_string, Cell(String::from("Meow x3Meow x3Meow x3Meow x3")))
}
#[test]
fn test_cell_multiply_negative() {
let cell_number: Cell<i32> = Cell(-3);
let cell_string: Cell<String> = Cell(String::from("kraB"));
assert_eq!(
cell_number * cell_string,
Cell(String::from("BarkBarkBark"))
)
}
#[test]
fn test_cell_multiply_zero() {
let cell_number: Cell<i32> = Cell(0);
let cell_string: Cell<String> = Cell(String::from("Silence!"));
assert_eq!(cell_number * cell_string, Cell(String::from("")))
}
#[test]
fn test_matrix_addition_positive() {
let matrix_number: Matrix<i32> = Matrix::new(&[1, 2, 3, 4]);
let matrix_string: Matrix<String> = Matrix::new(&[
String::from("one"),
String::from("two"),
String::from("three"),
String::from("four"),
]);
assert_eq!(
(matrix_number + matrix_string).by_row(),
vec![
Cell(String::from("1 one")),
Cell(String::from("2 two")),
Cell(String::from("3 three")),
Cell(String::from("4 four"))
]
);
}
#[test]
fn test_matrix_multiply_positive() {
let matrix_number: Matrix<i32> = Matrix::new(&[1, 2, 3, 1]);
let matrix_string: Matrix<String> = Matrix::new(&[
String::from("one"),
String::from("two"),
String::from("three"),
String::from("you get it"),
]);
assert_eq!(
matrix_number * matrix_string,
"one threethree twotwotwo you get it"
);
}
#[test]
fn test_matrix_multiply_zeros() {
let matrix_number: Matrix<i32> = Matrix::new(&[0, 0, 0, 0]);
let matrix_string: Matrix<String> = Matrix::new(&[
String::from("one"),
String::from("two"),
String::from("three"),
String::from("you get it"),
]);
assert_eq!(
matrix_number * matrix_string,
" "
);
}
}

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

Compiling solution v0.1.0 (/tmp/d20220112-2706256-1ndot2s/solution)
    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 ... 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 коментар)

Елизабет качи първо решение на 18.11.2021 12:49 (преди почти 4 години)

Добре е, че си написала тестове, включително умножение с нула и отрицателни числа 👍. Нещо, което ти липсва, са тестове с unicode (примерно кирилица или emoji). Добра идея са при всякаква форма на низова манипулация, като обръщане например.