Решение на Matrix 4 от Георги Бойчев

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

Към профила на Георги Бойчев

Резултати

  • 17 точки от тестове
  • 0 бонус точки
  • 17 точки общо
  • 13 успешни тест(а)
  • 2 неуспешни тест(а)

Код

use std::ops::Add;
use std::ops::Mul;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
row: Vec<T>,
row2: 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> {
let mut only_row: Vec<T> = Vec::new();
let mut only_row2: Vec<T> = Vec::new();
let mut counter: i32 = 0;
let data_copy = data.to_vec();
for i in data_copy{
if counter < 2{
only_row.push(i);
}
else {
only_row2.push(i);
}
counter+=1;
}
Matrix{
row: only_row,
row2: only_row2
}
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по редове,
/// от ляво надясно и от горе надолу, обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_row` да върне елементите в ред: 1, 2, 3, 4
///
pub fn by_row(&self) -> Vec<Cell<T>> {
let row_copy = self.row.clone();
let row2_copy = self.row2.clone();
let mut res: Vec<Cell<T>> = Vec::new();
for i in row_copy{
res.push(Cell(i));
}
for p in row2_copy{
res.push(Cell(p));
}
res
}
/// Връща вектор, който съдържа в себе си всички 4 елемента на матрицата, наредени по колони,
/// от горе надолу и от ляво надясно, Обвити в `Cell`. Тоест, ако матрицата изглежда така:
///
/// | 1 2 |
/// | 3 4 |
///
/// Очакваме `.by_col` да върне елементите в ред: 1, 3, 2, 4
///
pub fn by_col(&self) -> Vec<Cell<T>> {
let row_copy = self.row.clone();
let row2_copy = self.row2.clone();
let mut res: Vec<Cell<T>> = Vec::new();
let mut counter = 0;
for i in row_copy{
if counter == 1{
break;
}
if counter == 0{
res.push(Cell(i));
counter+=1;
}
}
for p in row2_copy{
if counter == 2{
break;
}
if counter == 1{
res.push(Cell(p));
counter+=1;
}
}
let row_copy = self.row.clone();
let row2_copy = self.row2.clone();
for s in row_copy{
if counter == 3{
break;
}
if counter == 2{
res.push(Cell(s));
counter+=1;
}
}
for p in row2_copy{
if counter == 4{
break;
}
if counter == 3{
res.push(Cell(p));
counter+=1;
}
}
res
}
}
impl Add<Cell<String>> for Cell<i32> { // Имплементирай ми "добавяне на Cell String към Cell i32"
type Output = Cell<String>; // Като резултата ще е винаги Cell String
fn add(self, rhs: Cell<String>) -> Cell<String> {
let num = self.0;
let mut result: String = String::new();
if num >= 0 {
let rhs_str = rhs.0;
result = num.to_string();
result.push_str(" ");
result.push_str(&rhs_str);
}
else {
for i in rhs.0.chars().rev(){
result.push(i);
}
result.push_str(" ");
result.push_str(&num.abs().to_string());
}
Cell(result)
}
}
impl Mul<Cell<String>> for Cell<i32> { // Имплементирай ми "умножение на Cell String към Cell i32"
type Output = Cell<String>; // Като резултата ще е винаги Cell string
fn mul(self, rhs: Cell<String>) -> Cell<String> {
let num = self.0;
let mut result: String = String::new();
if num >= 0 {
let rhs_str = rhs.0;
let mut count = 0;
while count < num{
result.push_str(&rhs_str);
count += 1;
}
}
else {
let mut reverse_str: String = String::new();
for i in rhs.0.chars().rev(){
reverse_str.push(i);
}
let mut count = 0;
while count < num.abs(){
result.push_str(&reverse_str);
count += 1;
}
}
Cell(result)
}
}
impl Add<Matrix<String>> for Matrix<i32> { // Имплементирай ми "добавяне на Matrix String към Matrix i32"
type Output = Matrix<String>; // Като резултата ще е винаги Matrix String
fn add(self, rhs: Matrix<String>) -> Matrix<String> {
let first_mat = self.by_row();
let second_mat = rhs.by_row();
let c_00 = first_mat[0].clone()+second_mat[0].clone();
let c_01 = first_mat[1].clone()+second_mat[1].clone();
let c_10 = first_mat[2].clone()+second_mat[2].clone();
let c_11 = first_mat[3].clone()+second_mat[3].clone();
Matrix{
row: vec![c_00.0, c_01.0],
row2: vec![c_10.0, c_11.0]
}
}
}
impl Mul<Matrix<String>> for Matrix<i32> { // Имплементирай ми "умножение на Matrix String към Matrix i32"
type Output = String; // Като резултата ще е винаги String
fn mul(self, rhs: Matrix<String>) -> String {
let first_mat = self.by_row();
let second_mat = rhs.by_row();
let c_00 = first_mat[0].clone()*second_mat[0].clone();
let c_01 = first_mat[1].clone()*second_mat[2].clone();
let c_10 = first_mat[2].clone()*second_mat[1].clone();
let c_11 = first_mat[3].clone()*second_mat[3].clone();
let mut result = String::new();
result.push_str(&c_00.0);
result.push_str(" ");
result.push_str(&c_01.0);
result.push_str(" ");
result.push_str(&c_10.0);
result.push_str(" ");
result.push_str(&c_11.0);
result
}
}

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

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

failures:

---- solution_test::test_iterating_i32s stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[Cell(1), Cell(3), Cell(1), Cell(3)]`,
 right: `[Cell(1), Cell(3), Cell(2), Cell(4)]`', tests/solution_test.rs:21:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_iterating_strings stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[Cell("a"), Cell("c"), Cell("a"), Cell("c")]`,
 right: `[Cell("a"), Cell("c"), Cell("b"), Cell("d")]`', tests/solution_test.rs:31:5


failures:
    solution_test::test_iterating_i32s
    solution_test::test_iterating_strings

test result: FAILED. 13 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s

error: test failed, to rerun pass '--test solution_test'

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

Георги качи първо решение на 18.11.2021 15:18 (преди почти 4 години)