Решение на Matrix 4 от Атанас Тумбалев
Към профила на Атанас Тумбалев
Резултати
- 7 точки от тестове
- 0 бонус точки
- 7 точки общо
- 5 успешни тест(а)
- 10 неуспешни тест(а)
Код
use std::{ops::Add, ops::Mul};
use std::iter;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
elements: Vec<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 {
elements: Vec::from(data.clone())
}
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
self.elements.clone().into_iter().map(|e| Cell(e)).collect()
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
vec![
Cell(self.elements[1].clone()),
Cell(self.elements[3].clone()),
Cell(self.elements[2].clone()),
Cell(self.elements[4].clone()),
]
}
}
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(format!("{} {}", other.0, self.0)),
_ => Cell(format!("{} {}", other.0.chars().rev().collect::<String>(), self.0.abs()))
}
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(iter::repeat(other.0).take(self.0 as usize).collect()),
_ => Cell(iter::repeat::<String>(other.0.chars().rev().collect()).take(self.0.abs() as usize).collect())
}
}
}
impl Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, other: Matrix<String>) -> Matrix<String> {
let lhs = self.by_row();
let rhs = other.by_row();
let arr: [String; 4] = [
(lhs[0].clone() + rhs[0].clone()).0,
(lhs[1].clone() + rhs[1].clone()).0,
(lhs[2].clone() + rhs[2].clone()).0,
(lhs[3].clone() + rhs[3].clone()).0,
];
Matrix::new(&arr)
}
}
impl Mul<Matrix<String>> for Matrix<i32> {
type Output = String;
fn mul(self, other: Matrix<String>) -> String {
let lhs = self.by_row();
let rhs = other.by_col();
format!("{} {} {} {}",
(lhs[0].clone() * rhs[0].clone()).0,
(lhs[1].clone() * rhs[1].clone()).0,
(lhs[2].clone() * rhs[2].clone()).0,
(lhs[3].clone() * rhs[3].clone()).0)
}
}
#[test]
fn test_creation() {
let str = String::from("много обичам ягоди");
println!("{}", str);
let cell = Cell(str);
let cell2 = Cell(-4);
let cell_sum = cell2 + cell;
println!("{:?}", cell_sum);
println!("{}", cell_sum.0)
}
Лог от изпълнението
Compiling solution v0.1.0 (/tmp/d20220112-2706256-1jx7k6b/solution) Finished test [unoptimized + debuginfo] target(s) in 9.01s 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 ... FAILED test solution_test::test_adding_int_and_string_unicode ... FAILED test solution_test::test_adding_int_and_string_zero ... FAILED test solution_test::test_adding_matrices_1 ... FAILED test solution_test::test_adding_matrices_2 ... FAILED test solution_test::test_blank_strings ... FAILED test solution_test::test_iterating_i32s ... FAILED test solution_test::test_iterating_strings ... FAILED 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_adding_int_and_string_positive stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `"badger 4"`, right: `"4 badger"`', tests/solution_test.rs:39:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ---- solution_test::test_adding_int_and_string_unicode stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `"опа 0"`, right: `"0 опа"`', tests/solution_test.rs:62:5 ---- solution_test::test_adding_int_and_string_zero stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `"badger 0"`, right: `"0 badger"`', tests/solution_test.rs:47:5 ---- solution_test::test_adding_matrices_1 stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `[Cell("one 1"), Cell("two 2"), Cell("three 3"), Cell("four 4")]`, right: `[Cell("1 one"), Cell("2 two"), Cell("3 three"), Cell("4 four")]`', tests/solution_test.rs:114:5 ---- solution_test::test_adding_matrices_2 stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `[Cell("едно 1"), Cell("две 0"), Cell(" 3"), Cell(" иритеч 37")]`, right: `[Cell("1 едно"), Cell("0 две"), Cell(" 3"), Cell(" иритеч 37")]`', tests/solution_test.rs:125:5 ---- solution_test::test_blank_strings stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `" 573"`, right: `"573 "`', tests/solution_test.rs:103:5 ---- solution_test::test_iterating_i32s stdout ---- thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', /tmp/d20220112-2706256-1jx7k6b/solution/src/lib.rs:55:18 ---- solution_test::test_iterating_strings stdout ---- thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/lib.rs:55:18 ---- solution_test::test_multiplying_matrices_1 stdout ---- thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/lib.rs:55:18 ---- solution_test::test_multiplying_matrices_2 stdout ---- thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/lib.rs:55:18 failures: solution_test::test_adding_int_and_string_positive solution_test::test_adding_int_and_string_unicode solution_test::test_adding_int_and_string_zero solution_test::test_adding_matrices_1 solution_test::test_adding_matrices_2 solution_test::test_blank_strings solution_test::test_iterating_i32s solution_test::test_iterating_strings solution_test::test_multiplying_matrices_1 solution_test::test_multiplying_matrices_2 test result: FAILED. 5 passed; 10 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s error: test failed, to rerun pass '--test solution_test'
История (3 версии и 2 коментара)
Атанас качи решение на 18.11.2021 16:46 (преди почти 4 години)
use std::{ops::Add, ops::Mul};
use std::iter;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
elements: Vec<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 {
elements: Vec::from(data.clone())
}
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
self.elements.clone().into_iter().map(|e| Cell(e)).collect()
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
vec![
Cell(self.elements[1].clone()),
Cell(self.elements[3].clone()),
Cell(self.elements[2].clone()),
Cell(self.elements[4].clone()),
]
}
}
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(format!("{} {}", other.0, self.0)),
_ => Cell(format!("{} {}", other.0.chars().rev().collect::<String>(), self.0.abs()))
}
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(iter::repeat(other.0).take(self.0 as usize).collect()),
_ => Cell(iter::repeat::<String>(other.0.chars().rev().collect()).take(self.0.abs() as usize).collect())
}
}
}
+impl Add<Matrix<String>> for Matrix<i32> {
+ type Output = Matrix<String>;
+
+ fn add(self, other: Matrix<String>) -> Matrix<String> {
+ let lhs = self.by_row();
+ let rhs = other.by_row();
+ let arr: [String; 4] = [
+ (lhs[0].clone() + rhs[0].clone()).0,
+ (lhs[1].clone() + rhs[1].clone()).0,
+ (lhs[2].clone() + rhs[2].clone()).0,
+ (lhs[3].clone() + rhs[3].clone()).0,
+ ];
+ Matrix::new(&arr)
+ }
+}
+
#[test]
fn test_creation() {
let str = String::from("много обичам ягоди");
println!("{}", str);
let cell = Cell(str);
let cell2 = Cell(-4);
let cellSum = cell2 + cell;
println!("{:?}", cellSum);
println!("{}", cellSum.0)
}
Решението ти не се компилира, защото нямаш имплементация на Mul за матрици. Ако няма да го довършиш, сложи празна имплементация с todo!()
иначе ще получиш 0 точки.
Атанас качи решение на 18.11.2021 16:52 (преди почти 4 години)
use std::{ops::Add, ops::Mul};
use std::iter;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
elements: Vec<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 {
elements: Vec::from(data.clone())
}
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
self.elements.clone().into_iter().map(|e| Cell(e)).collect()
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
vec![
Cell(self.elements[1].clone()),
Cell(self.elements[3].clone()),
Cell(self.elements[2].clone()),
Cell(self.elements[4].clone()),
]
}
}
impl Add<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn add(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(format!("{} {}", other.0, self.0)),
_ => Cell(format!("{} {}", other.0.chars().rev().collect::<String>(), self.0.abs()))
}
}
}
impl Mul<Cell<String>> for Cell<i32> {
type Output = Cell<String>;
fn mul(self, other: Cell<String>) -> Cell<String> {
match self.0 {
0.. => Cell(iter::repeat(other.0).take(self.0 as usize).collect()),
_ => Cell(iter::repeat::<String>(other.0.chars().rev().collect()).take(self.0.abs() as usize).collect())
}
}
}
impl Add<Matrix<String>> for Matrix<i32> {
type Output = Matrix<String>;
fn add(self, other: Matrix<String>) -> Matrix<String> {
let lhs = self.by_row();
let rhs = other.by_row();
let arr: [String; 4] = [
(lhs[0].clone() + rhs[0].clone()).0,
(lhs[1].clone() + rhs[1].clone()).0,
(lhs[2].clone() + rhs[2].clone()).0,
(lhs[3].clone() + rhs[3].clone()).0,
];
Matrix::new(&arr)
}
}
+impl Mul<Matrix<String>> for Matrix<i32> {
+ type Output = String;
+
+ fn mul(self, other: Matrix<String>) -> String {
+ let lhs = self.by_row();
+ let rhs = other.by_col();
+
+ format!("{} {} {} {}",
+ (lhs[0].clone() * rhs[0].clone()).0,
+ (lhs[1].clone() * rhs[1].clone()).0,
+ (lhs[2].clone() * rhs[2].clone()).0,
+ (lhs[3].clone() * rhs[3].clone()).0)
+
+ }
+}
+
#[test]
fn test_creation() {
let str = String::from("много обичам ягоди");
println!("{}", str);
let cell = Cell(str);
let cell2 = Cell(-4);
- let cellSum = cell2 + cell;
- println!("{:?}", cellSum);
+ let cell_sum = cell2 + cell;
- println!("{}", cellSum.0)
+ println!("{:?}", cell_sum);
-}
+ println!("{}", cell_sum.0)
+}
+
Компилира ли се вече, малко забравих за домашното