Итериране на матрици

Краен срок
09.12.2021 17:00
Точки
4

Срокът за предаване на решения е отминал

use solution::*;
#[test]
fn test_iteration_1() {
let data = [1, 2,
3, 4,
5, 6];
let matrix = Matrix::new(3, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &5, &2, &4, &6]);
}
#[test]
fn test_iteration_2() {
let data = [1, 2, 3,
4, 5, 6];
let matrix = Matrix::new(2, 3, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &4, &2, &5, &3, &6]);
}
#[test]
fn test_iteration_3() {
let data = ["1", "2", "3",
"4", "5", "6",
"7", "8", "9"];
let matrix = Matrix::new(3, 3, &data);
assert_eq!(
matrix.by_row().collect::<Vec<_>>(),
vec![&"1", &"2", &"3", &"4", &"5", &"6", &"7", &"8", &"9"]
);
assert_eq!(
matrix.by_col().collect::<Vec<_>>(),
vec![&"1", &"4", &"7", &"2", &"5", &"8", &"3", &"6", &"9"]
);
}

За предното домашно, вместо .by_row() и .by_col() да връщаха вектори, щеше да е доста по-гъвкаво да са итератори -- кеф ти да ги collect-неш във вектор, кеф ти да ги итерираш по reference. Но решихме, че ще е ненужна допълнителна работа и може да остане за предизвикателство.

Ето го и него:

#[derive(Debug)]
pub struct Matrix<T> {
    // каквото ви трябва
}

impl<T: Clone> Matrix<T> {
    /// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
    /// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
    /// Ако искате да panic-нете при невалиден вход, ваш избор.
    ///
    /// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
    /// така че си ги клонирайте и си ги наредете както ви е удобно.
    ///
    pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
        todo!()
    }

    pub fn by_row(&self) -> RowIter<T> {
        todo!()
    }

    pub fn by_col(&self) -> ColIter<T> {
        todo!()
    }
}

pub struct RowIter<T> {
    // каквото ви трябва
}

pub struct ColIter<T> {
    // каквото ви трябва
}

Очакваме да имплементирате Iterator trait-а и за RowIter, и за ColIter, като ще трябва да итерирате по reference. Ще трябва да промените малко типовете по-горе за да сложите нужните lifetimes. Не би трябвало да е особено изненадващо -- имаме примери за имплементиране на итератори из видеата.

Ето един примерен test, който би трябвало да се компилира и да работи:

#[test]
fn test_iteration_0() {
    let data = [1, 2,
                3, 4];
    let matrix = Matrix::new(2, 2, &data);

    assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
    assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}

Решения

Андрей
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Андрей

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
data: Vec<T>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Matrix { rows, cols, data: data[0 .. (rows * cols)].to_vec() }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter { matrix: self, current: 0 }
}
pub fn by_col(&self) -> ColIter<T> {
ColIter { matrix: self, current: 0 }
}
}
pub struct RowIter<'a, T> {
matrix: &'a Matrix<T>,
current: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let item = self.matrix.data.get(self.current);
self.current += 1;
item
}
}
pub struct ColIter<'a, T> {
matrix: &'a Matrix<T>,
current: usize,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let current_row = self.current % self.matrix.rows;
let current_col = self.current / self.matrix.rows;
if current_col >= self.matrix.cols {
return None;
}
let item = self.matrix.data.get(current_row * self.matrix.cols + current_col);
self.current += 1;
item
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1rs81f/solution)
    Finished test [unoptimized + debuginfo] target(s) in 4.09s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Димо Чанев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Димо Чанев

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
cells: Vec<T>,
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut res = Matrix {
rows,
cols,
cells: vec![],
};
for i in 0..rows {
for j in 0..cols {
res.cells.push(data[i * cols + j].clone());
}
}
res
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
mat: &self,
row: 0,
col: 0,
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
mat: &self,
row: 0,
col: 0,
}
}
}
pub struct RowIter<'a, T> {
mat: &'a Matrix<T>,
row: usize,
col: usize,
}
pub struct ColIter<'a, T> {
mat: &'a Matrix<T>,
row: usize,
col: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> std::option::Option<Self::Item> {
let res = if self.row < self.mat.rows && self.col < self.mat.cols {
Some(&self.mat.cells[self.row * self.mat.cols + self.col])
} else {
None
};
self.col += 1;
if self.col == self.mat.cols {
self.row += 1;
self.col = 0;
}
res
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> std::option::Option<Self::Item> {
let res = if self.row < self.mat.rows && self.col < self.mat.cols {
Some(&self.mat.cells[self.row * self.mat.cols + self.col])
} else {
None
};
self.row += 1;
if self.row == self.mat.rows {
self.col += 1;
self.row = 0;
}
res
}
}
#[cfg(test)]
mod tests {
use crate::Matrix;
#[test]
fn test_iteration_0() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-2x540o/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.96s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Павел Сарлов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Павел Сарлов

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
data: Vec<T>,
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
assert!(rows * cols == data.len());
Matrix {
rows,
cols,
data: data.clone()
.iter()
.map(|x| x.to_owned())
.collect()
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
curr: 0,
matrix: self,
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
curr: 0,
matrix: self,
}
}
}
pub struct RowIter<'a, T> {
// каквото ви трябва
curr: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let result = match self.curr < self.matrix.rows * self.matrix.cols {
true => Some(&self.matrix.data[self.curr]),
_ => None,
};
self.curr += 1;
result
}
}
pub struct ColIter<'a, T> {
// каквото ви трябва
curr: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let cell = (self.curr % self.matrix.rows) * self.matrix.cols + self.curr / self.matrix.rows;
let result = match self.curr < self.matrix.rows * self.matrix.cols {
true => Some(&self.matrix.data[cell]),
_ => None,
};
self.curr += 1;
result
}
}
#[cfg(test)]
mod mytests {
use super::*;
#[test]
fn test_iter() {
let mat = Matrix::new(2, 3, &[1, 2, 3, 4, 5, 6]);
assert_eq!(mat.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6]);
assert_eq!(mat.by_col().collect::<Vec<_>>(), vec![&1, &4, &2, &5, &3, &6]);
assert_eq!(mat.by_row().map(|x| x*2).collect::<Vec<_>>(), vec![2, 4, 6, 8, 10, 12]);
}
#[test]
fn test_next() {
let mat = Matrix::new(2, 3, &[1, 2, 3, 4, 5, 6]);
let mut it = mat.by_row();
assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&4));
assert_eq!(it.next(), Some(&5));
assert_eq!(it.next(), Some(&6));
assert_eq!(it.next(), None);
assert_eq!(it.next(), None);
let mut it = mat.by_col();
assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&4));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&5));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&6));
assert_eq!(it.next(), None);
assert_eq!(it.next(), None);
}
#[test]
fn test_invalid_data_size() {
assert!(std::panic::catch_unwind(|| Matrix::new(1,1,&[1,2])).is_err());
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1qk0i61/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.94s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Ростислав Цачев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ростислав Цачев

#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<Vec<T>>,
rows: usize,
cols: usize
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut data_index = 0;
let mut matrix_data = Vec::new();
for row in 0..rows {
matrix_data.push(Vec::new());
for _ in 0..cols {
matrix_data[row].push(data[data_index].clone());
data_index += 1;
}
}
Matrix { data: matrix_data, rows, cols }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter { matrix: &self, row: 0, col: 0 }
}
pub fn by_col(&self) -> ColIter<T> {
ColIter { matrix: &self, row: 0, col: 0 }
}
}
pub struct RowIter<'a, T: 'a> {
matrix: &'a Matrix<T>,
row: usize,
col: usize
}
impl<'a, T: 'a> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.row < self.matrix.rows && self.col < self.matrix.cols {
let row = self.row;
let col = self.col;
self.col += 1;
if self.col >= self.matrix.cols {
self.row += 1;
if self.row < self.matrix.rows {
self.col = 0;
}
}
Some(&self.matrix.data[row][col])
} else {
None
}
}
}
pub struct ColIter<'a, T: 'a> {
matrix: &'a Matrix<T>,
row: usize,
col: usize
}
impl<'a, T: 'a> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.row * self.col < self.matrix.rows * self.matrix.cols {
let row = self.row;
let col = self.col;
self.row += 1;
if self.row >= self.matrix.rows {
self.col += 1;
if self.col < self.matrix.cols {
self.row = 0;
}
}
Some(&self.matrix.data[row][col])
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_iteration_0() {
let data = [1, 2,
3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
fn test_iteration_by_ref() {
let data = [1, 2, 3, 4,
5, 6, 7, 8];
let matrix = Matrix::new(2, 4, &data);
let expected_by_row = [1, 2, 3, 4, 5, 6, 7, 8];
let mut index = 0;
for element in matrix.by_row() {
assert_eq!(*element, expected_by_row[index]);
index += 1;
}
let expected_by_col = [1, 5, 2, 6, 3, 7, 4, 8];
index = 0;
for element in matrix.by_col() {
assert_eq!(*element, expected_by_col[index]);
index += 1;
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-m0zt89/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.02s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Павел Атанасов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Павел Атанасов

use std::collections::VecDeque;
#[derive(Debug)]
pub struct Matrix<T: Clone> {
data: Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
assert_eq!(data.len(), rows * cols);
Matrix {
data: data
.clone()
.chunks(cols)
.map(|row| row.to_owned())
.collect(),
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
data: self
.data
.iter()
.map(|row| row.iter().collect())
.collect(),
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
data: self
.data
.iter()
.map(|row| row.iter().collect())
.collect(),
rows: self.data.len(),
current_row: 0,
}
}
}
pub struct RowIter<'a, T> {
data: VecDeque<VecDeque<&'a T>>,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
// If data is cleared or there is just one empty row -> End
if self.data.len() == 0 || (self.data.len() == 1 && self.data[0].len() == 0) {
self.data.clear();
return None;
}
if self.data[0].len() == 0 {
self.data.pop_front();
}
self.data[0].pop_front()
}
}
pub struct ColIter<'a, T> {
data: VecDeque<VecDeque<&'a T>>,
current_row: usize,
rows: usize,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
// If data is cleared or last row is empty -> End
if self.data.len() == 0 || self.data[self.rows - 1].len() == 0 {
self.data.clear();
return None;
}
let return_value = self.data[self.current_row].pop_front();
self.current_row = (self.current_row + 1) % self.rows;
return_value
}
}
#[cfg(test)]
mod tests {
use crate::{ColIter, Matrix, RowIter};
#[test]
fn test_iteration_0() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
#[should_panic]
fn test_invalid_array_size() {
Matrix::new(2, 2, &[1, 2, 3, 4, 5]);
}
#[test]
fn test_matrix_by_row() {
let mat = Matrix::new(2, 2, &[1, 2, 3, 4]);
assert_eq!(mat.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
}
#[test]
fn test_matrix_by_col() {
let mat = Matrix::new(2, 2, &[1, 2, 3, 4]);
assert_eq!(mat.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
fn test_matrix_by_row_next_after_none() {
let mat = Matrix::new(3, 2, &[1, 2, 3, 4, 5, 6]);
let mut rows: RowIter<i32> = mat.by_row();
assert_eq!(rows.next(), Some(&1));
assert_eq!(rows.next(), Some(&2));
assert_eq!(rows.next(), Some(&3));
assert_eq!(rows.next(), Some(&4));
assert_eq!(rows.next(), Some(&5));
assert_eq!(rows.next(), Some(&6));
assert_eq!(rows.next(), None);
assert_eq!(rows.next(), None);
}
#[test]
fn test_matrix_by_col_next_after_none() {
let mat = Matrix::new(3, 2, &[1, 2, 3, 4, 5, 6]);
let mut cols: ColIter<i32> = mat.by_col();
assert_eq!(cols.next(), Some(&1));
assert_eq!(cols.next(), Some(&3));
assert_eq!(cols.next(), Some(&5));
assert_eq!(cols.next(), Some(&2));
assert_eq!(cols.next(), Some(&4));
assert_eq!(cols.next(), Some(&6));
assert_eq!(cols.next(), None);
assert_eq!(cols.next(), None);
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1vwfy64/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.74s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Стоян Грозданов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Стоян Грозданов

#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<T>,
rows: usize,
cols: usize,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
if rows == 0 || cols == 0 {
panic!("{}", "Invalid matrix data");
}
Matrix { data: data.to_vec(), rows, cols }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter { data: &self.data, index: 0 }
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
data: &self.data,
row_index: 0,
rows: self.rows,
col_index: 0,
cols: self.cols
}
}
}
pub struct RowIter<'a, T> {
data: &'a [T],
index: usize,
}
pub struct ColIter<'a, T> {
data: &'a [T],
row_index: usize,
rows: usize,
col_index: usize,
cols: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.data.len() {
None
} else {
let item = &self.data[self.index];
self.index += 1;
Some(item)
}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.col_index >= self.cols {
None
} else {
let index = self.row_index * self.cols + self.col_index;
let item = &self.data[index];
self.row_index += 1;
if self.row_index >= self.rows {
self.row_index = 0;
self.col_index += 1;
}
Some(item)
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-18l3egc/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.99s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Даниел Пенчев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Даниел Пенчев

#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<Vec<T>>
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
if (rows != 0 && cols == 0) || (rows == 0 && cols != 0) || rows * cols != data.len() {
panic!("Invalid input params")
}
let mut matrix: Vec<Vec<T>> = Vec::new();
let mut curr_row = vec![];
for i in 0..data.len(){
if i % cols == 0 && i > 0 {
matrix.push(curr_row);
curr_row = vec![];
}
curr_row.push(data[i].clone());
}
matrix.push(curr_row);
Matrix{
data: matrix,
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(&self.data)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(&self.data)
}
}
pub struct ColIter<'a, T> {
items: Vec<&'a T>
}
impl<'a,T> Iterator for ColIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.items.pop()
}
}
impl<'a, T> ColIter<'a, T>{
fn new<'b>(data: &'b Vec<Vec<T>>) -> ColIter<'b, T>{
if data.len() == 0 {
return ColIter{ items: vec![] }
}
let mut items: Vec<Vec<&T>> = Vec::new();
let columns = data[0].len();
let rows = data.len();
for columnIdx in 0..columns{
let mut column_items = vec![];
for rowIdx in 0..rows {
column_items.push(&data[rowIdx][columnIdx])
}
items.push(column_items)
}
let result: Vec<&'b T> = items.into_iter().flatten().rev().collect();
ColIter{ items: result}
}
}
pub struct RowIter<'a, T> {
items: Vec<&'a T>
}
impl<'a, T> RowIter<'a, T>{
fn new<'b>(data: &'b Vec<Vec<T>>) -> RowIter<'b, T>{
let items: Vec<&'b T> = data.iter().flatten().rev().collect();
RowIter{ items }
}
}
impl<'a,T> Iterator for RowIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.items.pop()
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-9stlqt/solution)
warning: variable `columnIdx` should have a snake case name
  --> src/lib.rs:66:13
   |
66 |         for columnIdx in 0..columns{
   |             ^^^^^^^^^ help: convert the identifier to snake case: `column_idx`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `rowIdx` should have a snake case name
  --> src/lib.rs:68:17
   |
68 |             for rowIdx in 0..rows {
   |                 ^^^^^^ help: convert the identifier to snake case: `row_idx`

warning: `solution` (lib) generated 2 warnings
    Finished test [unoptimized + debuginfo] target(s) in 2.64s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Мариян Момчилов
  • Некоректно
  • 1 успешни тест(а)
  • 2 неуспешни тест(а)
Мариян Момчилов

#[derive(Debug)]
pub struct Matrix<T> {
buff: Vec<Vec<T>>
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut buff = Vec::<Vec<T>>::new();
for i in 0..rows {
let row = Vec::<T>::from_iter(data[i*rows..i*rows + cols].iter().map(|x| x.clone()));
buff.push(row);
}
Matrix{buff}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter{buff: &self.buff, crr_row: 0, crr_col: 0}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter{buff: &self.buff, crr_row: 0, crr_col: 0}
}
}
pub struct RowIter<'a, T> {
crr_row: usize,
crr_col: usize,
buff: &'a Vec<Vec<T>>
}
impl<'a, T: Clone> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.crr_row < self.buff.len() && self.crr_col < self.buff[self.crr_row].len() {
let val = &self.buff[self.crr_row][self.crr_col];
self.crr_col = (self.crr_col + 1) % self.buff[self.crr_row].len();
if self.crr_col == 0 {
self.crr_row += 1;
}
return Some(val);
}
None
}
}
pub struct ColIter<'a, T> {
crr_row: usize,
crr_col: usize,
buff: &'a Vec<Vec<T>>
}
impl<'a, T: Clone> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.crr_row < self.buff.len() && self.crr_col < self.buff[self.crr_row].len() {
let val = &self.buff[self.crr_row][self.crr_col];
self.crr_row = (self.crr_row + 1) % self.buff.len();
if self.crr_row == 0 {
self.crr_col += 1;
}
return Some(val);
}
None
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-fxbbqx/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.02s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... FAILED
test solution_test::test_iteration_2 ... FAILED
test solution_test::test_iteration_3 ... ok

failures:

---- solution_test::test_iteration_1 stdout ----
thread 'main' panicked at 'range end index 8 out of range for slice of length 6', /tmp/d20211209-3212651-fxbbqx/solution/src/lib.rs:10:43
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_iteration_2 stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[1, 2, 3, 3, 4, 5]`,
 right: `[1, 2, 3, 4, 5, 6]`', tests/solution_test.rs:21:5


failures:
    solution_test::test_iteration_1
    solution_test::test_iteration_2

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

error: test failed, to rerun pass '--test solution_test'
Аристотелис Папанис
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Аристотелис Папанис

#[derive(Debug)]
pub struct Matrix<T> {
by_cols: Vec<T>, //правя си два вектора за да пазя матрицата
by_rows: Vec<T>, //и по колони и в ориганлания вид (по редове)
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
assert_eq!(rows * cols, data.len());
//тука запазвам по колони
//идеята е да направя цикличен итератор и да обхождам оригиналния slice
//добавям елемент към вектора , после прескачам останалите които не ми трябват
//добавям следващия и това го правя rows*size пъти
let mut vec2: Vec<T> = Vec::new();
let mut iter = data.iter().cloned().cycle().into_iter();
for i in 1..=rows * cols {
vec2.push(iter.clone().next().unwrap());
for _k in 0..cols {
iter.next();
}
if i % rows == 0 {
iter.next();
}
}
Matrix::<T> {
by_cols: vec2.clone(),
by_rows: data.iter().cloned().collect::<Vec<_>>(),
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::<T> {
rows: &self.by_rows,
index: 0,
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::<T> {
cols: &self.by_cols,
index: 0,
}
}
}
pub struct RowIter<'a, T> {
rows: &'a Vec<T>,
index: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.rows.len() {
let old_index = self.index;
self.index += 1;
return Some(&self.rows[old_index]);
}
None
}
}
pub struct ColIter<'a, T> {
cols: &'a Vec<T>,
index: usize,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.cols.len() {
let old_index = self.index;
self.index += 1;
return Some(&self.cols[old_index]);
}
None
}
}
#[cfg(test)]
mod tests {
use crate::Matrix;
#[test]
fn test_iteration_0() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
fn test_iteration_1() {
let data = [1, 2, 3, 4, 5, 6];
let matrix = Matrix::new(3, 2, &data);
assert_eq!(
matrix.by_row().collect::<Vec<_>>(),
vec![&1, &2, &3, &4, &5, &6]
);
assert_eq!(
matrix.by_col().collect::<Vec<_>>(),
vec![&1, &3, &5, &2, &4, &6]
);
}
#[test]
fn test_4rows_1col() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(4, 1, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
}
#[test]
fn test_1row_4cols() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(1, 4, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
}
#[test]
fn test_manual_iteration_by_rows() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(2, 2, &data);
let mut iter = matrix.by_row();
assert_eq!(Some(&1), iter.next());
assert_eq!(Some(&2), iter.next());
assert_eq!(Some(&3), iter.next());
assert_eq!(Some(&4), iter.next());
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
}
#[test]
fn test_manual_iteration_by_cols() {
let data = [1, 2, 3, 4];
let matrix = Matrix::new(2, 2, &data);
let mut iter = matrix.by_col();
assert_eq!(Some(&1), iter.next());
assert_eq!(Some(&3), iter.next());
assert_eq!(Some(&2), iter.next());
assert_eq!(Some(&4), iter.next());
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
}
#[test]
fn test_kirilica() {
let data = ["едно", "две", "три", "четири"];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&"едно", &"две", &"три", &"четири"]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&"едно", &"три", &"две", &"четири"]);
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1cnz7sz/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.41s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Кристиян Цветанов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Кристиян Цветанов

#[derive(Debug)]
pub struct Matrix<T> {
matrix:Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut v: Vec<Vec<T>> = Vec::new();
let mut i = 0;
while i < rows {
let mut temp_vec: Vec<T> = Vec::new();
let mut j = 0;
while j < cols {
temp_vec.push(data[i*cols+j].clone());
j = j+1;
}
v.push(temp_vec);
i = i+1;
}
Self { matrix: v }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::<T>::new(&self.matrix)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::<T>::new(&self.matrix)
}
}
pub struct RowIter<'a, T> {
rows: &'a Vec<Vec<T>>,
vert_pos: usize,
hor_pos: usize,
}
impl<'a, T> RowIter<'a, T> {
pub fn new(matrix: &'a Vec<Vec<T>>) -> Self {
Self {
rows: matrix,
vert_pos: 0,
hor_pos: 0,
}
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let rows_num = self.rows.len();
let cols_num = self.rows[0].len();
let result;
if self.vert_pos < rows_num {
result = Some(&self.rows[self.vert_pos][self.hor_pos]);
self.hor_pos += 1;
if self.hor_pos == cols_num {
self.hor_pos = 0;
self.vert_pos += 1;
}
} else {
result = None;
}
result
}
}
pub struct ColIter<'a, T> {
cols: &'a Vec<Vec<T>>,
vert_pos: usize,
hor_pos: usize,
}
impl<'a, T> ColIter<'a, T> {
pub fn new(matrix: &'a Vec<Vec<T>>) -> Self {
Self {
cols: matrix,
vert_pos: 0,
hor_pos: 0,
}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let rows_num = self.cols.len();
let cols_num = self.cols[0].len();
let result;
if self.hor_pos < cols_num {
result = Some(&self.cols[self.vert_pos][self.hor_pos]);
self.vert_pos += 1;
if self.vert_pos == rows_num {
self.vert_pos = 0;
self.hor_pos += 1;
}
} else {
result = None;
}
result
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-r7ti8v/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.01s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Мирослав Дионисиев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Мирослав Дионисиев

#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_iteration_0()
{
let data = [1, 2, 3,
5, 3, 4];
let matrix = Matrix::new(2, 3, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &5, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &5, &2, &3, &3, &4]);
}
}
#[derive(Debug)]
pub struct Matrix<T>
{
pub data: Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T>
{
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self
{
Matrix
{
data: data
.clone()
.chunks(cols)
.map(|row| row.to_owned())
.collect(),
}
}
pub fn by_row(&self) -> RowIter<T>
{
RowIter{matrix: self, row: 0, col: 0}
}
pub fn by_col(&self) -> ColIter<T>
{
ColIter{matrix: self, row: 0, col: 0}
}
}
pub struct RowIter<'a, T>
{
matrix: &'a Matrix<T>,
row: usize,
col: usize,
}
impl<'a, T> Iterator for RowIter<'a, T>
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item>
{
self.col+=1;
if self.col > self.matrix.data[0].len()
{
self.col=1;
self.row+=1;
}
if self.row < self.matrix.data.len() && self.col <= self.matrix.data[0].len()
{
Some(&self.matrix.data[self.row][self.col-1])
}
else
{
None
}
}
}
pub struct ColIter<'a, T>
{
matrix: &'a Matrix<T>,
row: usize,
col: usize,
}
impl<'a, T> Iterator for ColIter<'a, T>
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item>
{
self.row+=1;
if self.row > self.matrix.data.len()
{
self.row=1;
self.col+=1;
}
if self.row <= self.matrix.data.len() && self.col < self.matrix.data[0].len()
{
Some(&self.matrix.data[self.row-1][self.col])
}
else
{
None
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-160zmnp/solution)
warning: unused variable: `rows`
  --> src/lib.rs:26:16
   |
26 |     pub fn new(rows: usize, cols: usize, data: &[T]) -> Self 
   |                ^^^^ help: if this is intentional, prefix it with an underscore: `_rows`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: `solution` (lib) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 2.97s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Наделина Шипочка
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Наделина Шипочка

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
data: Vec<T>
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut v: Vec<T> = Vec::new();
for elem in data{
v.push(elem.clone());
}
Matrix{
cols,
rows,
data: v
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(self)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(self)
}
}
pub struct RowIter<'a, T> {
matrix: Vec<&'a T>
}
impl<'a, T: Clone> RowIter<'a, T>{
pub fn new(matrix:&'a Matrix<T>) -> Self{
let mut v: Vec<&T> = Vec::new();
for i in 0..matrix.rows {
for j in 0..matrix.cols{
v.push(&matrix.data[i * matrix.cols + j])
}
}
RowIter{
matrix: v
}
}
}
impl<'a, T: Clone> Iterator for RowIter<'a, T>{
type Item = &'a T;
fn next (&mut self) -> Option<&'a T> {
if self.matrix.len() == 0{
None
}
else {
let elem = self.matrix[0];
self.matrix.remove(0);
Some(elem)
}
}
}
pub struct ColIter<'a, T> {
matrix: Vec<&'a T>
}
impl<'a, T: Clone> ColIter<'a, T>{
pub fn new(matrix:&'a Matrix<T>) -> Self{
let mut v: Vec<&T> = Vec::new();
for j in 0..matrix.cols {
for i in 0..matrix.rows{
v.push(&matrix.data[i * matrix.cols + j]);
}
}
ColIter{
matrix: v
}
}
}
impl<'a, T: Clone> Iterator for ColIter<'a, T>{
type Item = &'a T;
fn next (&mut self) -> Option<&'a T> {
if self.matrix.len() == 0{
None
}
else {
let elem = self.matrix[0];
self.matrix.remove(0);
Some(elem)
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1p99vn7/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.92s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Николай Натов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Николай Натов

#[derive(Debug)]
pub struct Matrix<T>
{
m_Data: Vec<T>,
m_Rows: usize,
m_Cols: usize
}
impl<T: Clone> Matrix<T>
{
pub fn new(rows: usize, cols: usize, data: &[T]) -> Matrix<T>
{
let mut matrixData: Vec<T> = Vec::new();
matrixData.reserve(cols * rows);
for i in 0..rows * cols
{
matrixData.push(data[i].clone());
}
return Matrix {
m_Data: matrixData,
m_Rows: rows,
m_Cols: cols
};
}
pub fn by_row(&self) -> RowIter<T>
{
return RowIter::new(self);
}
pub fn by_col(&self) -> ColIter<T>
{
return ColIter::new(self);
}
}
pub struct RowIter<'a, T: 'a>
{
pub Matrix: &'a Matrix<T>,
pub CurrentIndex: usize,
}
impl<'a, T: Clone> RowIter<'a, T>
{
pub fn new(matrix: &'a Matrix<T>) -> RowIter<'a, T>
{
return RowIter {
Matrix: matrix,
CurrentIndex: 0
}
}
}
impl<'a, T: Clone> Iterator for RowIter<'a, T>
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item>
{
if self.CurrentIndex >= self.Matrix.m_Cols * self.Matrix.m_Rows
{
return None;
}
let nextValue: &T = &self.Matrix.m_Data[self.CurrentIndex];
self.CurrentIndex += 1;
return Some(nextValue);
}
}
pub struct ColIter<'a, T: 'a>
{
pub Matrix: &'a Matrix<T>,
pub CurrentRow: usize,
pub CurrentCol: usize
}
impl<'a, T: Clone> ColIter<'a, T>
{
pub fn new(matrix: &'a Matrix<T>) -> ColIter<'a, T>
{
return ColIter {
Matrix: matrix,
CurrentRow: 0,
CurrentCol: 0,
}
}
}
impl<'a, T: Clone> Iterator for ColIter<'a, T>
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item>
{
if self.CurrentCol == self.Matrix.m_Cols
{
return None;
}
let nextValue: &T = &self.Matrix.m_Data[self.CurrentCol + self.CurrentRow * self.Matrix.m_Cols];
self.CurrentRow += 1;
if self.CurrentRow == self.Matrix.m_Rows
{
self.CurrentRow = 0;
self.CurrentCol += 1;
}
return Some(nextValue);
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-uz87ta/solution)
warning: structure field `m_Data` should have a snake case name
 --> src/lib.rs:4:5
  |
4 |     m_Data: Vec<T>,
  |     ^^^^^^ help: convert the identifier to snake case: `m_data`
  |
  = note: `#[warn(non_snake_case)]` on by default

warning: structure field `m_Rows` should have a snake case name
 --> src/lib.rs:5:5
  |
5 |     m_Rows: usize,
  |     ^^^^^^ help: convert the identifier to snake case: `m_rows`

warning: structure field `m_Cols` should have a snake case name
 --> src/lib.rs:6:5
  |
6 |     m_Cols: usize
  |     ^^^^^^ help: convert the identifier to snake case (notice the capitalization): `m_cols`

warning: variable `matrixData` should have a snake case name
  --> src/lib.rs:13:17
   |
13 |         let mut matrixData: Vec<T> = Vec::new();
   |                 ^^^^^^^^^^ help: convert the identifier to snake case: `matrix_data`

warning: structure field `Matrix` should have a snake case name
  --> src/lib.rs:41:9
   |
41 |     pub Matrix: &'a Matrix<T>,
   |         ^^^^^^ help: convert the identifier to snake case: `matrix`

warning: structure field `CurrentIndex` should have a snake case name
  --> src/lib.rs:42:9
   |
42 |     pub CurrentIndex: usize,
   |         ^^^^^^^^^^^^ help: convert the identifier to snake case: `current_index`

warning: variable `nextValue` should have a snake case name
  --> src/lib.rs:68:13
   |
68 |         let nextValue: &T = &self.Matrix.m_Data[self.CurrentIndex];
   |             ^^^^^^^^^ help: convert the identifier to snake case: `next_value`

warning: structure field `Matrix` should have a snake case name
  --> src/lib.rs:76:9
   |
76 |     pub Matrix: &'a Matrix<T>,
   |         ^^^^^^ help: convert the identifier to snake case: `matrix`

warning: structure field `CurrentRow` should have a snake case name
  --> src/lib.rs:77:9
   |
77 |     pub CurrentRow: usize,
   |         ^^^^^^^^^^ help: convert the identifier to snake case: `current_row`

warning: structure field `CurrentCol` should have a snake case name
  --> src/lib.rs:78:9
   |
78 |     pub CurrentCol: usize
   |         ^^^^^^^^^^ help: convert the identifier to snake case: `current_col`

warning: variable `nextValue` should have a snake case name
   --> src/lib.rs:104:13
    |
104 |         let nextValue: &T = &self.Matrix.m_Data[self.CurrentCol + self.CurrentRow * self.Matrix.m_Cols];
    |             ^^^^^^^^^ help: convert the identifier to snake case: `next_value`

warning: `solution` (lib) generated 11 warnings
    Finished test [unoptimized + debuginfo] target(s) in 2.65s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Александър Стоилов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Александър Стоилов

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
vec: Vec<T>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut vec: Vec<T> = vec![];
for i in data {
vec.push(i.clone());
}
Self { rows, cols, vec }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(0, self)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(self.cols, 0, self)
}
}
pub struct RowIter<'a, T> {
idx: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> RowIter<'a, T> {
fn new(idx: usize, matrix: &'a Matrix<T>) -> Self {
Self { idx, matrix }
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.idx == self.matrix.vec.len() {
None
} else {
let item = &self.matrix.vec[self.idx];
self.idx += 1;
Some(item)
}
}
}
pub struct ColIter<'a, T> {
col: usize,
idx: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> ColIter<'a, T> {
fn new(col: usize, idx: usize, matrix: &'a Matrix<T>) -> Self {
Self { col, idx, matrix }
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let last_index = self.matrix.vec.len() - 1;
if self.idx >= self.matrix.vec.len() {
None
} else {
let item = &self.matrix.vec[self.idx];
if self.idx == last_index - self.col {
self.idx = last_index;
} else if self.idx == last_index {
self.idx += 1;
} else {
self.idx = (self.idx + self.col) % last_index;
}
Some(item)
}
}
}
#[test]
fn _test_iteration_0() {
let data = [1, 2, 3, 4, 5, 6, 7, 8];
let matrix = Matrix::new(4, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6, &7, &8]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &5, &7, &2, &4, &6, &8]);
}
#[test]
fn _test_iteration_1() {
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
let matrix = Matrix::new(3, 6, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6, &7, &8, &9, &10, &11, &12, &13, &14, &15, &16, &17, &18]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &7, &13, &2, &8, &14, &3, &9, &15, &4, &10, &16, &5, &11, &17, &6, &12, &18]);
}
#[test]
fn _test_iteration_2() {
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323,
324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357,
358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391,
392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459,
460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493,
494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527,
528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561,
562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595,
596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629,
630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663,
664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697,
698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731,
732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765,
766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799,
800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867,
868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901,
902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935,
936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969,
970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000];
let matrix = Matrix::new(250, 4, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6, &7, &8, &9, &10, &11, &12, &13, &14, &15, &16, &17, &18, &19, &20, &21, &22, &23, &24, &25, &26, &27, &28, &29, &30, &31, &32, &33, &34, &35, &36, &37, &38, &39, &40, &41, &42, &43, &44, &45, &46, &47, &48, &49, &50, &51, &52, &53, &54, &55, &56, &57, &58, &59, &60, &61, &62, &63, &64, &65, &66, &67, &68, &69, &70, &71, &72, &73, &74, &75, &76, &77, &78, &79, &80, &81, &82, &83, &84, &85, &86, &87, &88, &89, &90, &91, &92, &93, &94, &95, &96, &97, &98, &99, &100, &101, &102, &103, &104, &105, &106, &107, &108, &109, &110, &111, &112, &113, &114, &115, &116, &117, &118, &119, &120, &121, &122, &123, &124, &125, &126, &127, &128, &129, &130, &131, &132, &133, &134, &135, &136, &137, &138, &139, &140, &141, &142, &143, &144, &145, &146, &147, &148, &149, &150, &151, &152, &153, &154, &155, &156, &157, &158, &159, &160, &161, &162, &163, &164, &165, &166, &167, &168, &169, &170, &171, &172, &173, &174, &175, &176, &177, &178, &179, &180, &181, &182, &183, &184, &185, &186, &187, &188, &189, &190, &191, &192, &193, &194, &195, &196, &197, &198, &199, &200, &201, &202, &203, &204, &205, &206, &207, &208, &209, &210, &211, &212, &213, &214, &215, &216, &217, &218, &219, &220, &221, &222, &223, &224, &225, &226, &227, &228, &229, &230, &231, &232, &233, &234, &235, &236, &237, &238, &239, &240, &241, &242, &243, &244, &245, &246, &247, &248, &249, &250, &251, &252, &253, &254, &255, &256, &257, &258, &259, &260, &261, &262, &263, &264, &265, &266, &267, &268, &269, &270, &271, &272, &273, &274, &275, &276, &277, &278, &279, &280, &281, &282, &283, &284, &285, &286, &287, &288, &289, &290, &291, &292, &293, &294, &295, &296, &297, &298, &299, &300, &301, &302, &303, &304, &305, &306, &307, &308, &309, &310, &311, &312, &313, &314, &315, &316, &317, &318, &319, &320, &321, &322, &323, &324, &325, &326, &327, &328, &329, &330, &331, &332, &333, &334, &335, &336, &337, &338, &339, &340, &341, &342, &343, &344, &345, &346, &347, &348, &349, &350, &351, &352, &353, &354, &355, &356, &357, &358, &359, &360, &361, &362, &363, &364, &365, &366, &367, &368, &369, &370, &371, &372, &373, &374, &375, &376, &377, &378, &379, &380, &381, &382, &383, &384, &385, &386, &387, &388, &389, &390, &391, &392, &393, &394, &395, &396, &397, &398, &399, &400, &401, &402, &403, &404, &405, &406, &407, &408, &409, &410, &411, &412, &413, &414, &415, &416, &417, &418, &419, &420, &421, &422, &423, &424, &425, &426, &427, &428, &429, &430, &431, &432, &433, &434, &435, &436, &437, &438, &439, &440, &441, &442, &443, &444, &445, &446, &447, &448, &449, &450, &451, &452, &453, &454, &455, &456, &457, &458, &459, &460, &461, &462, &463, &464, &465, &466, &467, &468, &469, &470, &471, &472, &473, &474, &475, &476, &477, &478, &479, &480, &481, &482, &483, &484, &485, &486, &487, &488, &489, &490, &491, &492, &493, &494, &495, &496, &497, &498, &499, &500, &501, &502, &503, &504, &505, &506, &507, &508, &509, &510, &511, &512, &513, &514, &515, &516, &517, &518, &519, &520, &521, &522, &523, &524, &525, &526, &527, &528, &529, &530, &531, &532, &533, &534, &535, &536, &537, &538, &539, &540, &541, &542, &543, &544, &545, &546, &547, &548, &549, &550, &551, &552, &553, &554, &555, &556, &557, &558, &559, &560, &561, &562, &563, &564, &565, &566, &567, &568, &569, &570, &571, &572, &573, &574, &575, &576, &577, &578, &579, &580, &581, &582, &583, &584, &585, &586, &587, &588, &589, &590, &591, &592, &593, &594, &595, &596, &597, &598, &599, &600, &601, &602, &603, &604, &605, &606, &607, &608, &609, &610, &611, &612, &613, &614, &615, &616, &617, &618, &619, &620, &621, &622, &623, &624, &625, &626, &627, &628, &629, &630, &631, &632, &633, &634, &635, &636, &637, &638, &639, &640, &641, &642, &643, &644, &645, &646, &647, &648, &649, &650, &651, &652, &653, &654, &655, &656, &657, &658, &659, &660, &661, &662, &663, &664, &665, &666, &667, &668, &669, &670, &671, &672, &673, &674, &675, &676, &677, &678, &679, &680, &681, &682, &683, &684, &685, &686, &687, &688, &689, &690, &691, &692, &693, &694, &695, &696, &697, &698, &699, &700, &701, &702, &703, &704, &705, &706, &707, &708, &709, &710, &711, &712, &713, &714, &715, &716, &717, &718, &719, &720, &721, &722, &723, &724, &725, &726, &727, &728, &729, &730, &731, &732, &733, &734, &735, &736, &737, &738, &739, &740, &741, &742, &743, &744, &745, &746, &747, &748, &749, &750, &751, &752, &753, &754, &755, &756, &757, &758, &759, &760, &761, &762, &763, &764, &765, &766, &767, &768, &769, &770, &771, &772, &773, &774, &775, &776, &777, &778, &779, &780, &781, &782, &783, &784, &785, &786, &787, &788, &789, &790, &791, &792, &793, &794, &795, &796, &797, &798, &799, &800, &801, &802, &803, &804, &805, &806, &807, &808, &809, &810, &811, &812, &813, &814, &815, &816, &817, &818, &819, &820, &821, &822, &823, &824, &825, &826, &827, &828, &829, &830, &831, &832, &833, &834, &835, &836, &837, &838, &839, &840, &841, &842, &843, &844, &845, &846, &847, &848, &849, &850, &851, &852, &853, &854, &855, &856, &857, &858, &859, &860, &861, &862, &863, &864, &865, &866, &867, &868, &869, &870, &871, &872, &873, &874, &875, &876, &877, &878, &879, &880, &881, &882, &883, &884, &885, &886, &887, &888, &889, &890, &891, &892, &893, &894, &895, &896, &897, &898, &899, &900, &901, &902, &903, &904, &905, &906, &907, &908, &909, &910, &911, &912, &913, &914, &915, &916, &917, &918, &919, &920, &921, &922, &923, &924, &925, &926, &927, &928, &929, &930, &931, &932, &933, &934, &935, &936, &937, &938, &939, &940, &941, &942, &943, &944, &945, &946, &947, &948, &949, &950, &951, &952, &953, &954, &955, &956, &957, &958, &959, &960, &961, &962, &963, &964, &965, &966, &967, &968, &969, &970, &971, &972, &973, &974, &975, &976, &977, &978, &979, &980, &981, &982, &983, &984, &985, &986, &987, &988, &989, &990, &991, &992, &993, &994, &995, &996, &997, &998, &999, &1000]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &5, &9, &13, &17, &21, &25, &29, &33, &37, &41, &45, &49, &53, &57, &61, &65, &69, &73, &77, &81, &85, &89, &93, &97,
&101, &105, &109, &113, &117, &121, &125, &129, &133, &137, &141, &145, &149, &153, &157, &161, &165, &169, &173, &177,
&181, &185, &189, &193, &197, &201, &205, &209, &213, &217, &221, &225, &229, &233, &237, &241, &245, &249, &253, &257,
&261, &265, &269, &273, &277, &281, &285, &289, &293, &297, &301, &305, &309, &313, &317, &321, &325, &329, &333, &337,
&341, &345, &349, &353, &357, &361, &365, &369, &373, &377, &381, &385, &389, &393, &397, &401, &405, &409, &413, &417,
&421, &425, &429, &433, &437, &441, &445, &449, &453, &457, &461, &465, &469, &473, &477, &481, &485, &489, &493, &497,
&501, &505, &509, &513, &517, &521, &525, &529, &533, &537, &541, &545, &549, &553, &557, &561, &565, &569, &573, &577,
&581, &585, &589, &593, &597, &601, &605, &609, &613, &617, &621, &625, &629, &633, &637, &641, &645, &649, &653, &657,
&661, &665, &669, &673, &677, &681, &685, &689, &693, &697, &701, &705, &709, &713, &717, &721, &725, &729, &733, &737,
&741, &745, &749, &753, &757, &761, &765, &769, &773, &777, &781, &785, &789, &793, &797, &801, &805, &809, &813, &817,
&821, &825, &829, &833, &837, &841, &845, &849, &853, &857, &861, &865, &869, &873, &877, &881, &885, &889, &893, &897,
&901, &905, &909, &913, &917, &921, &925, &929, &933, &937, &941, &945, &949, &953, &957, &961, &965, &969, &973, &977,
&981, &985, &989, &993, &997, &2, &6, &10, &14, &18, &22, &26, &30, &34, &38, &42, &46, &50, &54, &58, &62, &66, &70, &74,
&78, &82, &86, &90, &94, &98, &102, &106, &110, &114, &118, &122, &126, &130, &134, &138, &142, &146, &150, &154, &158,
&162, &166, &170, &174, &178, &182, &186, &190, &194, &198, &202, &206, &210, &214, &218, &222, &226, &230, &234, &238,
&242, &246, &250, &254, &258, &262, &266, &270, &274, &278, &282, &286, &290, &294, &298, &302, &306, &310, &314, &318,
&322, &326, &330, &334, &338, &342, &346, &350, &354, &358, &362, &366, &370, &374, &378, &382, &386, &390, &394, &398,
&402, &406, &410, &414, &418, &422, &426, &430, &434, &438, &442, &446, &450, &454, &458, &462, &466, &470, &474, &478,
&482, &486, &490, &494, &498, &502, &506, &510, &514, &518, &522, &526, &530, &534, &538, &542, &546, &550, &554, &558,
&562, &566, &570, &574, &578, &582, &586, &590, &594, &598, &602, &606, &610, &614, &618, &622, &626, &630, &634, &638,
&642, &646, &650, &654, &658, &662, &666, &670, &674, &678, &682, &686, &690, &694, &698, &702, &706, &710, &714, &718,
&722, &726, &730, &734, &738, &742, &746, &750, &754, &758, &762, &766, &770, &774, &778, &782, &786, &790, &794, &798,
&802, &806, &810, &814, &818, &822, &826, &830, &834, &838, &842, &846, &850, &854, &858, &862, &866, &870, &874, &878,
&882, &886, &890, &894, &898, &902, &906, &910, &914, &918, &922, &926, &930, &934, &938, &942, &946, &950, &954, &958,
&962, &966, &970, &974, &978, &982, &986, &990, &994, &998, &3, &7, &11, &15, &19, &23, &27, &31, &35, &39, &43, &47,
&51, &55, &59, &63, &67, &71, &75, &79, &83, &87, &91, &95, &99, &103, &107, &111, &115, &119, &123, &127, &131, &135,
&139, &143, &147, &151, &155, &159, &163, &167, &171, &175, &179, &183, &187, &191, &195, &199, &203, &207, &211, &215,
&219, &223, &227, &231, &235, &239, &243, &247, &251, &255, &259, &263, &267, &271, &275, &279, &283, &287, &291, &295,
&299, &303, &307, &311, &315, &319, &323, &327, &331, &335, &339, &343, &347, &351, &355, &359, &363, &367, &371, &375,
&379, &383, &387, &391, &395, &399, &403, &407, &411, &415, &419, &423, &427, &431, &435, &439, &443, &447, &451, &455,
&459, &463, &467, &471, &475, &479, &483, &487, &491, &495, &499, &503, &507, &511, &515, &519, &523, &527, &531, &535,
&539, &543, &547, &551, &555, &559, &563, &567, &571, &575, &579, &583, &587, &591, &595, &599, &603, &607, &611, &615,
&619, &623, &627, &631, &635, &639, &643, &647, &651, &655, &659, &663, &667, &671, &675, &679, &683, &687, &691, &695,
&699, &703, &707, &711, &715, &719, &723, &727, &731, &735, &739, &743, &747, &751, &755, &759, &763, &767, &771, &775,
&779, &783, &787, &791, &795, &799, &803, &807, &811, &815, &819, &823, &827, &831, &835, &839, &843, &847, &851, &855,
&859, &863, &867, &871, &875, &879, &883, &887, &891, &895, &899, &903, &907, &911, &915, &919, &923, &927, &931, &935,
&939, &943, &947, &951, &955, &959, &963, &967, &971, &975, &979, &983, &987, &991, &995, &999, &4, &8, &12, &16, &20,
&24, &28, &32, &36, &40, &44, &48, &52, &56, &60, &64, &68, &72, &76, &80, &84, &88, &92, &96, &100, &104, &108, &112,
&116, &120, &124, &128, &132, &136, &140, &144, &148, &152, &156, &160, &164, &168, &172, &176, &180, &184, &188, &192,
&196, &200, &204, &208, &212, &216, &220, &224, &228, &232, &236, &240, &244, &248, &252, &256, &260, &264, &268, &272,
&276, &280, &284, &288, &292, &296, &300, &304, &308, &312, &316, &320, &324, &328, &332, &336, &340, &344, &348, &352,
&356, &360, &364, &368, &372, &376, &380, &384, &388, &392, &396, &400, &404, &408, &412, &416, &420, &424, &428, &432,
&436, &440, &444, &448, &452, &456, &460, &464, &468, &472, &476, &480, &484, &488, &492, &496, &500, &504, &508, &512,
&516, &520, &524, &528, &532, &536, &540, &544, &548, &552, &556, &560, &564, &568, &572, &576, &580, &584, &588, &592,
&596, &600, &604, &608, &612, &616, &620, &624, &628, &632, &636, &640, &644, &648, &652, &656, &660, &664, &668, &672,
&676, &680, &684, &688, &692, &696, &700, &704, &708, &712, &716, &720, &724, &728, &732, &736, &740, &744, &748, &752,
&756, &760, &764, &768, &772, &776, &780, &784, &788, &792, &796, &800, &804, &808, &812, &816, &820, &824, &828, &832,
&836, &840, &844, &848, &852, &856, &860, &864, &868, &872, &876, &880, &884, &888, &892, &896, &900, &904, &908, &912,
&916, &920, &924, &928, &932, &936, &940, &944, &948, &952, &956, &960, &964, &968, &972, &976, &980, &984, &988, &992,
&996, &1000]);
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-owkadu/solution)
    Finished test [unoptimized + debuginfo] target(s) in 4.57s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Ангел Марински
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ангел Марински

#[derive(Debug)]
pub struct Matrix<T> {
vec: Vec<Vec<T>>,
rows: usize,
cols: usize,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut data_index = 0;
let mut matrix_data: Vec<Vec<T>> = Vec::<Vec<T>>::new();
matrix_data.resize(rows, Vec::new());
for row in 0..rows{
for _step in 0..cols {
matrix_data[row].push(data[data_index].clone());
data_index += 1;
}
}
Matrix { vec: matrix_data, rows, cols }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(0, 0, self)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(0, 0, self)
}
}
pub struct RowIter<'a, T> {
row: usize,
col: usize,
matrix: &'a Matrix<T>,
}
pub struct ColIter<'a, T> {
col: usize,
row: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> RowIter<'a, T> {
fn new(_row: usize, _col: usize, _matrix: &'a Matrix<T>) -> Self {
Self {row: _row, col: _col, matrix: _matrix}
}
}
impl<'a, T> ColIter<'a, T> {
fn new(_col: usize, _current_row: usize, _matrix: &'a Matrix<T>) -> Self {
Self {col: _col, row: _current_row, matrix: _matrix}
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.row <= self.matrix.rows - 1 && self.col <= self.matrix.cols - 1{
let item = &self.matrix.vec[self.row][self.col];
if self.col == self.matrix.cols - 1{
self.col = 0;
self.row += 1;
}
else{
self.col += 1;
}
Some(item)
}
else{
None
}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.row <= self.matrix.rows - 1 && self.col <= self.matrix.cols - 1 {
let item = &self.matrix.vec[self.row][self.col];
if self.row == self.matrix.rows - 1{
self.row = 0;
self.col += 1;
}
else{
self.row += 1;
}
Some(item)
}
else {
None
}
}
}
#[test]
fn test_iteration_0() {
let data = [1, 2, 3, 4, 5, 6, 7, 8];
let matrix = Matrix::new(4, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6, &7, &8]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &5, &7, &2, &4, &6, &8]);
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-17b1prv/solution)
    Finished test [unoptimized + debuginfo] target(s) in 4.48s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Никола Кралев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Никола Кралев

//#![allow(unused_variables)]
//#![allow(dead_code)]
//#![allow(non_snake_case)]
#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut result = Matrix::<T> {
data: Vec::with_capacity(rows),
};
for i in 0_usize..rows {
result.data.push(Vec::with_capacity(cols));
for j in 0_usize..cols {
result.data[i].push(data[i * cols + j].clone());
}
}
return result;
}
pub fn by_row(&self) -> RowIter<T> {
return RowIter::new(0_usize, 0_usize, &self);
}
pub fn by_col(&self) -> ColIter<T> {
return ColIter::new(0_usize, 0_usize, &self);
}
pub fn getRowCount(&self) -> usize {
return self.data.len();
}
pub fn getColCount(&self) -> usize {
return self.data[0].len();
}
}
#[derive(Debug)]
pub struct RowIter<'lifetimeMatrix, T> {
matrixRef: &'lifetimeMatrix Matrix<T>,
row: usize,
col: usize,
isFirst: bool, //this is a disgusting hack, but it works, also guarantees no overflows will happen
}
impl<'lifetimeMatrix, 'lifetimeSelf, T> RowIter<'lifetimeMatrix, T> {
pub fn new(
row: usize,
col: usize,
matrixRef: &'lifetimeMatrix Matrix<T>,
) -> RowIter<'lifetimeMatrix, T> {
return RowIter::<T> {
matrixRef: matrixRef,
row: row,
col: col,
isFirst: true,
};
}
}
impl<'lifetimeItem, T: Clone> Iterator for RowIter<'lifetimeItem, T> {
type Item = &'lifetimeItem T;
fn next(&mut self) -> Option<Self::Item> {
if self.isFirst {
self.isFirst = false;
return Some(&(self.matrixRef.data[self.row][self.col]));
}
//if we reached the end of the current row
if self.col == self.matrixRef.getColCount() - 1_usize {
//if we just finished the last row
if self.row == self.matrixRef.getRowCount() - 1_usize {
return None;
}
//go to the next row
self.row += 1_usize;
self.col = 0_usize;
} else {
//move to the next one from the current row
self.col += 1;
}
return Some(&(self.matrixRef.data[self.row][self.col]));
}
}
#[derive(Debug)]
pub struct ColIter<'lifetimeMatrix, T> {
matrixRef: &'lifetimeMatrix Matrix<T>,
row: usize,
col: usize,
isFirst: bool, //this is a disgusting hack, but it works, also guarantees no overflows will happen
}
impl<'lifetimeMatrix, 'lifetimeSelf, T> ColIter<'lifetimeMatrix, T> {
pub fn new(
row: usize,
col: usize,
matrixRef: &'lifetimeMatrix Matrix<T>,
) -> ColIter<'lifetimeMatrix, T> {
return ColIter::<T> {
matrixRef: matrixRef,
row: row,
col: col,
isFirst: true,
};
}
}
impl<'lifetimeItem, T: Clone> Iterator for ColIter<'lifetimeItem, T> {
type Item = &'lifetimeItem T;
fn next(&mut self) -> Option<Self::Item> {
if self.isFirst {
self.isFirst = false;
return Some(&(self.matrixRef.data[self.row][self.col]));
}
//if we reached the bottom of the current col
if self.row == self.matrixRef.getRowCount() - 1_usize {
//if we just finished the last column
if self.col == self.matrixRef.getColCount() - 1_usize {
return None;
}
//go to the next column
self.col += 1_usize;
self.row = 0_usize;
} else {
//move to the next one below from the current col
self.row += 1;
}
return Some(&(self.matrixRef.data[self.row][self.col]));
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-oalstf/solution)
warning: method `getRowCount` should have a snake case name
  --> src/lib.rs:33:12
   |
33 |     pub fn getRowCount(&self) -> usize {
   |            ^^^^^^^^^^^ help: convert the identifier to snake case: `get_row_count`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: method `getColCount` should have a snake case name
  --> src/lib.rs:37:12
   |
37 |     pub fn getColCount(&self) -> usize {
   |            ^^^^^^^^^^^ help: convert the identifier to snake case: `get_col_count`

warning: lifetime `'lifetimeMatrix` should have a snake case name
  --> src/lib.rs:43:20
   |
43 | pub struct RowIter<'lifetimeMatrix, T> {
   |                    ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_matrix`

warning: structure field `matrixRef` should have a snake case name
  --> src/lib.rs:44:5
   |
44 |     matrixRef: &'lifetimeMatrix Matrix<T>,
   |     ^^^^^^^^^ help: convert the identifier to snake case: `matrix_ref`

warning: structure field `isFirst` should have a snake case name
  --> src/lib.rs:47:5
   |
47 |     isFirst: bool, //this is a disgusting hack, but it works, also guarantees no overflows will happen
   |     ^^^^^^^ help: convert the identifier to snake case: `is_first`

warning: lifetime `'lifetimeMatrix` should have a snake case name
  --> src/lib.rs:50:6
   |
50 | impl<'lifetimeMatrix, 'lifetimeSelf, T> RowIter<'lifetimeMatrix, T> {
   |      ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_matrix`

warning: lifetime `'lifetimeSelf` should have a snake case name
  --> src/lib.rs:50:23
   |
50 | impl<'lifetimeMatrix, 'lifetimeSelf, T> RowIter<'lifetimeMatrix, T> {
   |                       ^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_self`

warning: variable `matrixRef` should have a snake case name
  --> src/lib.rs:54:9
   |
54 |         matrixRef: &'lifetimeMatrix Matrix<T>,
   |         ^^^^^^^^^ help: convert the identifier to snake case: `matrix_ref`

warning: lifetime `'lifetimeItem` should have a snake case name
  --> src/lib.rs:65:6
   |
65 | impl<'lifetimeItem, T: Clone> Iterator for RowIter<'lifetimeItem, T> {
   |      ^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_item`

warning: lifetime `'lifetimeMatrix` should have a snake case name
  --> src/lib.rs:92:20
   |
92 | pub struct ColIter<'lifetimeMatrix, T> {
   |                    ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_matrix`

warning: structure field `matrixRef` should have a snake case name
  --> src/lib.rs:93:5
   |
93 |     matrixRef: &'lifetimeMatrix Matrix<T>,
   |     ^^^^^^^^^ help: convert the identifier to snake case: `matrix_ref`

warning: structure field `isFirst` should have a snake case name
  --> src/lib.rs:96:5
   |
96 |     isFirst: bool, //this is a disgusting hack, but it works, also guarantees no overflows will happen
   |     ^^^^^^^ help: convert the identifier to snake case: `is_first`

warning: lifetime `'lifetimeMatrix` should have a snake case name
  --> src/lib.rs:99:6
   |
99 | impl<'lifetimeMatrix, 'lifetimeSelf, T> ColIter<'lifetimeMatrix, T> {
   |      ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_matrix`

warning: lifetime `'lifetimeSelf` should have a snake case name
  --> src/lib.rs:99:23
   |
99 | impl<'lifetimeMatrix, 'lifetimeSelf, T> ColIter<'lifetimeMatrix, T> {
   |                       ^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_self`

warning: variable `matrixRef` should have a snake case name
   --> src/lib.rs:103:9
    |
103 |         matrixRef: &'lifetimeMatrix Matrix<T>,
    |         ^^^^^^^^^ help: convert the identifier to snake case: `matrix_ref`

warning: lifetime `'lifetimeItem` should have a snake case name
   --> src/lib.rs:114:6
    |
114 | impl<'lifetimeItem, T: Clone> Iterator for ColIter<'lifetimeItem, T> {
    |      ^^^^^^^^^^^^^ help: convert the identifier to snake case: `'lifetime_item`

warning: `solution` (lib) generated 16 warnings
    Finished test [unoptimized + debuginfo] target(s) in 3.08s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Надежда Панделиева
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Надежда Панделиева

#[derive(Debug)]
pub struct Matrix<T> {
cols: usize,
rows: usize,
data: Vec<T>
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut new_matrix: Vec<T> = Vec::new();
for cell in data{
new_matrix.push(cell.clone());
}
Self {cols,rows,data:new_matrix}
}
pub fn by_row(&self) -> RowIter<T> {
return RowIter::new(0, self);
}
pub fn by_col (&self) -> ColIter<T> {
return ColIter::new(0, 0, self);
}
}
pub struct RowIter<'a, T>{
pub index: usize,
pub m: &'a Matrix<T> ,
}
impl<'a, T> RowIter<'a , T>{
pub fn new(index: usize, m: &'a Matrix<T>) -> Self{
Self{index, m }
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item =&'a T ;
fn next(&mut self) -> Option<Self::Item> {
if self.index == self.m.data.len() {
return None;
}else{
let cell = &self.m.data[self.index];
self.index += 1;
return Some(cell);
}
}
}
pub struct ColIter<'a, T>{
pub col: usize,
pub row: usize,
pub grid: &'a Matrix<T> ,
}
impl<'a, T> ColIter<'a , T>{
pub fn new(col: usize, row: usize, grid: &'a Matrix<T>) -> Self{
Self{ col,row, grid}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item =&'a T ;
fn next(&mut self) -> Option<Self::Item> {
if self.col == self.grid.cols {
return None;
} else {
let cell = &self.grid.data[self.col+ self.row*self.grid.cols];
self.row += 1;
if self.row == self.grid.rows{
self.row = 0;
self.col += 1;
}
return Some(cell);
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-2sh6hm/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.95s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Георги Събев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Събев

#[derive(Debug)]
pub struct Matrix<T> {
r: usize,
c: usize,
data: Vec<T>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let data_vec = data.clone().to_vec();
Matrix {
r: rows,
c: cols,
data: data_vec,
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(0, self)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(0, 0, self)
}
}
pub struct RowIter<'a, T> {
pos: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> RowIter<'a, T> {
fn new(pos: usize, matrix: &'a Matrix<T>) -> Self {
RowIter {
pos: pos,
matrix: matrix,
}
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.pos == self.matrix.data.len() {
return None;
}
let value = &self.matrix.data[self.pos];
self.pos += 1;
Some(value)
}
}
pub struct ColIter<'a, T> {
r: usize,
c: usize,
matrix: &'a Matrix<T>,
}
impl<'a, T> ColIter<'a, T> {
fn new(r: usize, c: usize, matrix: &'a Matrix<T>) -> Self {
ColIter {
r: r,
c: c,
matrix: matrix,
}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.r <= self.matrix.r - 1 && self.c <= self.matrix.c - 1 {
let value = &self.matrix.data[self.r * self.matrix.c + self.c];
if self.r == self.matrix.r - 1 {
self.r = 0;
self.c += 1;
} else {
self.r += 1;
}
return Some(value);
}
None
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-5gbtu9/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.84s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Васил Любенов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Васил Любенов

#[derive(Debug)]
pub struct Matrix<T> {
pub counter: usize,
pub rows: usize,
pub cols: usize,
pub my_data: Vec<T>,
}
impl<T: Clone + Copy> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Self{
counter: 0,
rows: rows,
cols: cols,
my_data: {
let mut my_vec = Vec::new();
for &elem in data {
my_vec.push(elem);
}
my_vec
}
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(&self.my_data, self.rows, self.cols)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(&self.my_data, self.rows, self.cols)
}
}
pub struct RowIter<'a, T> {
counter: usize,
rows: usize,
cols: usize,
my_vec: Vec<&'a T>,
}
impl<'a, T> RowIter<'a, T>{
pub fn new(vect: &'a Vec<T>, rows: usize, cols: usize) -> Self{
Self{
counter: 0,
rows: rows,
cols: cols,
my_vec: {
let mut my_vec = Vec::new();
for elem in vect{
my_vec.push(elem);
}
my_vec
}
}
}
}
impl<'a, T> Iterator for RowIter<'a, T>{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.counter < self.rows * self.cols{
let result = Some(self.my_vec[self.counter]);
self.counter += 1;
result
}
else{
None
}
}
}
pub struct ColIter<'a, T> {
counter: usize,
current_col: usize,
rows: usize,
cols: usize,
my_vec: Vec<&'a T>,
}
impl<'a, T> ColIter<'a, T>{
pub fn new(vect: &'a Vec<T>, rows: usize, cols: usize) -> Self{
Self{
counter: 0,
current_col: 0,
rows: rows,
cols: cols,
my_vec: {
let mut my_vec = Vec::new();
for elem in vect{
my_vec.push(elem);
}
my_vec
}
}
}
}
impl<'a, T> Iterator for ColIter<'a, T>{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current_col < self.cols {
let result = Some(self.my_vec[self.current_col + self.counter]);
self.counter += self.cols;
if self.counter > self.cols * (self.rows - 1){
self.current_col += 1;
self.counter = 0;
}
result
}
else{
None
}
}
}
//extra tests:
// let data = [0, 1, 2, 3, 4,
// 5, 6, 7, 8, 9,
// 10, 11, 12, 13, 14,
// 15, 16, 17, 18, 19];
//let matrix = Matrix::new(4, 5, &data);
//assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&0, &5, &10, &15, &1, &6, &11, &16, &2, &7, &12, &17, &3, &8, &13, &18, &4, &9, &14, &19]);
//assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&0, &1, &2, &3, &4, &5, &6, &7, &8, &9, &10, &11, &12, &13, &14, &15, &16, &17, &18, &19]);
Compiling solution v0.1.0 (/tmp/d20211209-3212651-118iiul/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.03s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Боян Дафов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Боян Дафов

#[derive(Debug)]
pub struct Matrix<T> {
pub elements : Vec<T>,
pub rows : usize,
pub cols : usize,
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut vec = Vec::new();
for elem in data {
vec.push(elem.clone());
}
let result = Matrix{elements : vec, rows : rows, cols : cols};
result
}
pub fn by_row(&self) -> RowIter<T> {
RowIter{elem : &self.elements, current : 0}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter{elem : &self.elements, current : 0, rows : self.rows, cols : self.cols}
}
}
use std::iter::Iterator;
pub struct RowIter<'a, T> {
// каквото ви трябва
pub elem : &'a Vec<T>,
pub current : usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.elem.len() {
return None
}
let res = self.elem.get(self.current);
self.current += 1;
res
}
}
pub struct ColIter<'a, T> {
// каквото ви трябва
pub elem : &'a Vec<T>,
pub current : usize,
pub rows : usize,
pub cols : usize,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= (self.rows * self.cols) {
return None
}
let res = self.elem.get(self.current);
if self.current == (self.rows * self.cols - 1) {
self.current += 1;
}else if self.current >= (self.cols * self.rows - self.cols) {
self.current -= self.cols * self.rows - self.cols - 1;
} else {
self.current += self.cols;
}
res
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-yc81rx/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.88s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Ивайло Петков
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ивайло Петков

#[derive(Debug)]
pub struct Matrix<T> {
cols: usize,
rows: usize,
data: Vec<T>
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let data: Vec<T> = data.into_iter().map(|x| x.clone()).collect();
Matrix {
cols,
rows,
data
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
current_element: 0,
matrix: self,
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
current_element: 0,
matrix: self,
}
}
}
pub struct RowIter<'a, T> {
current_element: usize,
matrix: &'a Matrix<T>
}
pub struct ColIter<'a, T> {
current_element: usize,
matrix: &'a Matrix<T>
}
impl<'a, T: 'a> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let row = self.current_element.div_euclid(self.matrix.cols);
let col = self.current_element.rem_euclid(self.matrix.cols);
if row >= self.matrix.rows || col >= self.matrix.cols {
None
} else {
self.current_element = self.current_element + 1;
Some(&self.matrix.data[row*self.matrix.cols + col])
}
}
}
impl<'a, T: 'a> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let row = self.current_element.rem_euclid(self.matrix.rows);
let col = self.current_element.div_euclid(self.matrix.rows);
if row >= self.matrix.rows || col >= self.matrix.cols {
None
} else {
self.current_element = self.current_element + 1;
Some(&self.matrix.data[row*self.matrix.cols + col])
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-dedbct/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.92s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Чудомир Ченков
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Чудомир Ченков

#[derive(Debug)]
pub struct Matrix<T> {
rows: usize,
cols: usize,
data: Vec<T>
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Matrix {
rows,
cols,
data: data.iter().cloned().collect()
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(self.data.iter().collect())
}
pub fn by_col(&self) -> ColIter<T> {
let mut data_by_col : Vec<&T> = Vec::new();
for i in 0..self.cols {
let mut cur : usize = i;
for _ in 0..self.rows {
data_by_col.push(&self.data[cur]);
cur += self.cols;
}
}
ColIter::new(data_by_col)
}
}
pub struct RowIter<'a, T> {
data: Vec<&'a T>,
index: usize
}
impl<'a, T: Clone> RowIter<'a, T> {
pub fn new(data: Vec<&'a T>) -> Self {
RowIter {
data,
index: 0
}
}
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
match self.data.get(self.index) {
Some(value) => {
self.index += 1;
Some(value)
}
None => None,
}
}
}
pub struct ColIter<'a, T> {
data: Vec<&'a T>,
index: usize
}
impl<'a, T: Clone> ColIter<'a, T> {
pub fn new(data: Vec<&'a T>) -> Self {
ColIter {
data,
index: 0
}
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
match self.data.get(self.index) {
Some(value) => {
self.index += 1;
Some(value)
}
None => None,
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-k6oma5/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.32s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Иван Стефанов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Иван Стефанов

#[derive(Debug)]
pub struct Matrix<T> {
matrix : Vec<T>,
rows : usize,
cols : usize,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Matrix { matrix: data.to_owned(), rows : rows, cols : cols}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {row_iter : &self,cur_index : 0 }
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {col_iter : &self,cur_index : 0 }
}
}
pub struct RowIter<'a, T> {
row_iter : &'a Matrix<T>,
cur_index : usize,
}
impl<'a, T : Clone> Iterator for RowIter<'a, T> where T: 'a
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.cur_index < self.row_iter.matrix.len() {
self.cur_index += 1;
Some(&self.row_iter.matrix[self.cur_index-1])
} else {
None
}
}
}
pub struct ColIter<'a, T> {
col_iter : &'a Matrix<T>,
cur_index : usize,
}
impl<'a, T : Clone> Iterator for ColIter<'a, T> where T: 'a
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.cur_index < self.col_iter.matrix.len() {
self.cur_index += 1;
Some(&self.col_iter.matrix[(self.cur_index-1)/self.col_iter.rows + (self.cur_index-1)%self.col_iter.rows * self.col_iter.cols])
} else {
None
}
}
}
#[cfg(test)]
mod my_tests{
mod iter_by_row_tests{
use crate::*;
#[test]
fn square_matrix_0(){
let data = ['🍕', '🍕', '🍕',
'🍔', '🍔', '🍔',
'🍟', '🍟', '🍟'];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍕', &'🍕',
&'🍔', &'🍔', &'🍔',
&'🍟', &'🍟', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn square_matrix_1(){
let data = ["Never", "gonna", "give",
"you", "up", "never",
"gonna", "let", "you down"];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&"Never", &"gonna", &"give",
&"you", &"up", &"never",
&"gonna", &"let", &"you down"];
assert_eq!(result, expected);
}
#[test]
fn square_matrix_2(){
let data = [Some(1), Some(2), Some(3),
Some(4), Some(5), None,
None, Some(8), None];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&Some(1), &Some(2), &Some(3),
&Some(4), &Some(5), &None,
&None, &Some(8), &None];
assert_eq!(result, expected);
}
#[test]
fn rectangle_matrix_0(){
let data = ['🍕', '🍕', '🍕', '🍕', '🍕',
'🍔', '🍔', '🍔', '🍔', '🍔',
'🍟', '🍟', '🍟', '🍟', '🍟'];
let matrix = Matrix::new(3, 5, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍕', &'🍕', &'🍕', &'🍕',
&'🍔', &'🍔', &'🍔', &'🍔', &'🍔',
&'🍟', &'🍟', &'🍟', &'🍟', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn rectangle_matrix_1(){
let data = ['🍕', '🍕', '🍕',
'🍔', '🍔', '🍔',
'🍟', '🍟', '🍟',
'🌭', '🍟', '🌭',
'🥓', '🥓', '🥓',
'🥓', '🍟', '🍟',
'🥓', '🍟', '🍟'];
let matrix = Matrix::new(7, 3, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍕', &'🍕',
&'🍔', &'🍔', &'🍔',
&'🍟', &'🍟', &'🍟',
&'🌭', &'🍟', &'🌭',
&'🥓', &'🥓', &'🥓',
&'🥓', &'🍟', &'🍟',
&'🥓', &'🍟', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn one_by_one_matrix(){
let data = [1];
let matrix = Matrix::new(1, 1, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<_> = vec![&1];
assert_eq!(result, expected);
}
#[test]
fn empty_matrix(){
let data: Vec<u32> = Vec::new();
let matrix = Matrix::new(0, 0, &data);
let result: Vec<_> = matrix.by_row().collect::<Vec<_>>();
let expected: Vec<&u32> = Vec::new();
assert_eq!(result, expected);
}
}
mod iter_by_col_tests{
use crate::*;
#[test]
fn square_matrix_0(){
let data = ['🍕', '🍕', '🍕',
'🍔', '🍔', '🍔',
'🍟', '🍟', '🍟'];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn square_matrix_1(){
let data = ["Never", "gonna", "give",
"you", "up", "never",
"gonna", "let", "you down"];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&"Never", &"you", &"gonna",
&"gonna", &"up", &"let",
&"give", &"never", &"you down"];
assert_eq!(result, expected);
}
#[test]
fn square_matrix_2(){
let data = [Some(1), Some(2), Some(3),
Some(4), Some(5), None,
None, Some(8), None];
let matrix = Matrix::new(3, 3, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&Some(1), &Some(4), &None,
&Some(2), &Some(5), &Some(8),
&Some(3), &None, &None];
assert_eq!(result, expected);
}
#[test]
fn rectangle_matrix_0(){
let data = ['🍕', '🍕', '🍕', '🍕', '🍕',
'🍔', '🍔', '🍔', '🍔', '🍔',
'🍟', '🍟', '🍟', '🍟', '🍟'];
let matrix = Matrix::new(3, 5, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟',
&'🍕', &'🍔', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn rectangle_matrix_1(){
let data = ['🍕', '🍕', '🍕',
'🍔', '🍔', '🍔',
'🍟', '🍟', '🍟',
'🌭', '🍟', '🌭',
'🥓', '🥓', '🥓',
'🥓', '🍟', '🍟',
'🥓', '🍟', '🍟'];
let matrix = Matrix::new(7, 3, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&'🍕', &'🍔', &'🍟', &'🌭', &'🥓', &'🥓', &'🥓',
&'🍕', &'🍔', &'🍟', &'🍟', &'🥓', &'🍟', &'🍟',
&'🍕', &'🍔', &'🍟', &'🌭', &'🥓', &'🍟', &'🍟'];
assert_eq!(result, expected);
}
#[test]
fn one_by_one_matrix(){
let data = [1];
let matrix = Matrix::new(1, 1, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<_> = vec![&1];
assert_eq!(result, expected);
}
#[test]
fn empty_matrix(){
let data: Vec<u32> = Vec::new();
let matrix = Matrix::new(0, 0, &data);
let result: Vec<_> = matrix.by_col().collect::<Vec<_>>();
let expected: Vec<&u32> = Vec::new();
assert_eq!(result, expected);
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1q0xpmw/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.82s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Волен Димитров
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Волен Димитров

#[derive(Debug)]
pub struct Matrix<T> {
matrix_rows: Vec<T>,
matrix_cols: Vec<T>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
if data.len() != rows * cols {
panic!("Invalid matrix")
}
let mut cols_data = Vec::new();
for i in 0..cols {
for x in 0..data.len() {
if x % cols == i {
cols_data.push(data[x].clone())
}
}
}
Matrix {
matrix_rows: data.clone().to_vec(),
matrix_cols: cols_data,
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {data: self, count: 0}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {data: self, count: 0}
}
}
pub struct RowIter<'a, T: 'a> {
data: &'a Matrix<T>,
count: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.count+=1;
if self.count-1 < self.data.matrix_rows.len() {
Some(&self.data.matrix_rows[self.count-1])
} else {
None
}
}
}
pub struct ColIter<'a, T: 'a> {
data: &'a Matrix<T>,
count: usize,
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.count+=1;
if self.count-1 < self.data.matrix_cols.len() {
Some(&self.data.matrix_cols[self.count-1])
} else {
None
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-mqvebj/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.91s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Петър Павлов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Петър Павлов

use std::slice::Iter;
#[derive(Debug)]
pub struct Matrix<T> {
data_row: Vec<T>,
data_col: Vec<T>,
rows: usize,
cols: usize
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut result_row = Vec::new();
let mut result_col = Vec::new();
for elem in data {
result_row.push(elem.clone());
}
for i in 0..cols {
for j in 0..rows {
result_col.push(data[i+j*cols].clone());
}
}
Matrix {data_row: result_row, data_col: result_col, rows, cols}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {slice_iter: self.data_row.iter()}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {slice_iter: self.data_col.iter()}
}
}
pub struct RowIter<'a, T> {
slice_iter: Iter<'a, T>
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.slice_iter.next()
}
}
pub struct ColIter<'a, T> {
slice_iter: Iter<'a, T>
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.slice_iter.next()
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1raurg3/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.42s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Алекс Петров
  • Некоректно
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)
Алекс Петров

#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<Vec<T>>,
cols: usize,
rows: usize
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
if data.len() != rows*cols || data.len() == 0 {
panic!("Wrong matrix size!");
}
let mut matrixData : Vec<Vec<T>> = Vec::new();
let mut currentVec : Vec<T> = Vec::new();
for i in 0..data.len() {
if i != 0 && i % cols == 0 {
matrixData.push(currentVec.clone());
currentVec = Vec::new();
}
currentVec.push(data[i].clone());
if i == data.len() -1 {
matrixData.push(currentVec.clone());
}
}
Self {
data: matrixData.clone(),
rows: matrixData.clone().len(),
cols: matrixData[0].clone().len()
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter{
data: self.data.clone(),
cols: self.cols.clone(),
rows: self.rows.clone(),
index: 0
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter{
data: self.data.clone(),
cols: self.cols.clone(),
rows: self.rows.clone(),
index: 0
}
}
}
pub struct RowIter<T> {
// каквото ви трябва
data: Vec<Vec<T>>,
index: usize,
cols: usize,
rows: usize
}
impl<T : Clone> Iterator for RowIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.cols * self.rows {
let row = self.index / self.rows as usize;
let result = self.data[row][self.index % self.cols].clone();
self.index += 1;
Some(result)
} else {
None
}
}
}
impl<T : Clone> Iterator for ColIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.cols * self.rows {
let row = self.index / self.rows as usize;
let result = self.data[self.index % self.cols][row].clone();
self.index += 1;
Some(result)
} else {
None
}
}
}
pub struct ColIter<T> {
// каквото ви трябва
data: Vec<Vec<T>>,
index: usize,
cols: usize,
rows: usize
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-hebsm7/solution)
warning: variable `matrixData` should have a snake case name
  --> src/lib.rs:21:17
   |
21 |         let mut matrixData : Vec<Vec<T>> = Vec::new();
   |                 ^^^^^^^^^^ help: convert the identifier to snake case: `matrix_data`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `currentVec` should have a snake case name
  --> src/lib.rs:22:17
   |
22 |         let mut currentVec : Vec<T> = Vec::new();
   |                 ^^^^^^^^^^ help: convert the identifier to snake case: `current_vec`

warning: `solution` (lib) generated 2 warnings
error[E0277]: can't compare `{integer}` with `&{integer}`
  --> tests/solution_test.rs:11:5
   |
11 |     assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6]);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
   |
   = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
   = note: required because of the requirements on the impl of `PartialEq<Vec<&{integer}>>` for `Vec<{integer}>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: can't compare `{integer}` with `&{integer}`
  --> tests/solution_test.rs:12:5
   |
12 |     assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &5, &2, &4, &6]);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
   |
   = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
   = note: required because of the requirements on the impl of `PartialEq<Vec<&{integer}>>` for `Vec<{integer}>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: can't compare `{integer}` with `&{integer}`
  --> tests/solution_test.rs:21:5
   |
21 |     assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4, &5, &6]);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
   |
   = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
   = note: required because of the requirements on the impl of `PartialEq<Vec<&{integer}>>` for `Vec<{integer}>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: can't compare `{integer}` with `&{integer}`
  --> tests/solution_test.rs:22:5
   |
22 |     assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &4, &2, &5, &3, &6]);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
   |
   = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
   = note: required because of the requirements on the impl of `PartialEq<Vec<&{integer}>>` for `Vec<{integer}>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: can't compare `str` with `&str`
  --> tests/solution_test.rs:32:5
   |
32 | /     assert_eq!(
33 | |         matrix.by_row().collect::<Vec<_>>(),
34 | |         vec![&"1", &"2", &"3", &"4", &"5", &"6", &"7", &"8", &"9"]
35 | |     );
   | |______^ no implementation for `str == &str`
   |
   = help: the trait `PartialEq<&str>` is not implemented for `str`
   = note: required because of the requirements on the impl of `PartialEq<&&str>` for `&str`
   = note: 1 redundant requirements hidden
   = note: required because of the requirements on the impl of `PartialEq<Vec<&&str>>` for `Vec<&str>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: can't compare `str` with `&str`
  --> tests/solution_test.rs:36:5
   |
36 | /     assert_eq!(
37 | |         matrix.by_col().collect::<Vec<_>>(),
38 | |         vec![&"1", &"4", &"7", &"2", &"5", &"8", &"3", &"6", &"9"]
39 | |     );
   | |______^ no implementation for `str == &str`
   |
   = help: the trait `PartialEq<&str>` is not implemented for `str`
   = note: required because of the requirements on the impl of `PartialEq<&&str>` for `&str`
   = note: 1 redundant requirements hidden
   = note: required because of the requirements on the impl of `PartialEq<Vec<&&str>>` for `Vec<&str>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.
error: could not compile `solution` due to 6 previous errors
Георги Чобанов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Чобанов

#[derive(Debug)]
pub struct Matrix<T> {
matrix : Vec<Vec<T>>
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut new_matrix: Vec<Vec<T>> = Vec::new();
for _i in 0..rows {
new_matrix.push(Vec::new());
}
for i in 0..rows {
for j in 0..cols {
if (i*cols+j) > data.len() {
unreachable!();
}
new_matrix[i].push(data[i*cols+j].clone())
}
}
Matrix {matrix: new_matrix}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::new(&self.matrix)
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::new(&self.matrix)
}
}
pub struct RowIter<'a,T> {
index_row: usize,
index_col: usize,
elements: &'a Vec<Vec<T>>
}
pub struct ColIter<'a,T> {
index_row: usize,
index_col: usize,
elements: &'a Vec<Vec<T>>
}
impl<'a, T> RowIter<'a,T> {
fn new(data: &'a Vec<Vec<T>>) -> Self {
RowIter {
index_row: 0,
index_col: 0,
elements: data
}
}
}
impl<'a,T> Iterator for RowIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index_row >= self.elements.len() {
None
}
else {
if self.index_col >= self.elements[self.index_row].len() {
self.index_row += 1;
if self.index_row >= self.elements.len() {
None
}
else {
self.index_col = 1;
Some(&self.elements[self.index_row][self.index_col-1])
}
} else {
self.index_col += 1;
Some(&self.elements[self.index_row][self.index_col-1])
}
}
}
}
impl<'a, T> ColIter<'a,T> {
fn new(data: &'a Vec<Vec<T>>) -> Self {
ColIter {
index_row: 0,
index_col: 0,
elements: data
}
}
}
impl<'a,T> Iterator for ColIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index_row >= self.elements.len() {
self.index_row = 1;
self.index_col += 1;
if self.index_col >= self.elements[self.index_row].len() {
return None;
}
Some(&self.elements[self.index_row-1][self.index_col])
}
else
{
self.index_row += 1;
Some(&self.elements[self.index_row-1][self.index_col])
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-2q53dc/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.92s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Марио Николов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Марио Николов

#[derive(Debug)]
pub struct Matrix<T> {
matrix : Vec<T>,
rows : usize,
cols : usize
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Matrix::<T>{
rows : rows,
cols : cols,
matrix : {
let mut t1 = Vec::new();
for i in 0..data.len() {
t1.push(data[i].clone())
}
t1
}
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter::<T>{
matrix: &self,
index : 0
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter::<T>{
matrix: &self,
index : 0,
current_row : 0,
current_col : 0
}
}
}
pub struct RowIter<'a, T> {
matrix :&'a Matrix<T>,
index : usize
}
impl<'a, T: Clone> Iterator for RowIter<'a, T>{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
while self.index < self.matrix.matrix.len() {
self.index+=1;
return Some(&self.matrix.matrix[self.index-1]);
}
None
}
}
pub struct ColIter<'a, T> {
matrix : &'a Matrix<T>,
index : usize,
current_row : usize,
current_col : usize
}
impl<'a, T: Clone> Iterator for ColIter<'a, T>{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
while self.index + 1 < self.matrix.matrix.len() {
if self.current_row == self.matrix.rows {
self.current_row=0;
self.current_col+=1;
}
if self.current_col == self.matrix.cols {
self.current_col=0;
}
self.index = self.current_row*self.matrix.cols + self.current_col;
self.current_row+=1;
return Some(&self.matrix.matrix[self.index]);
}
None
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-klkro2/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.81s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Георги Бойчев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Бойчев

#[derive(Debug)]
pub struct Matrix<T> {
matrix_data: Vec<T>,
row_num: i32,
col_num: i32
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
Matrix { matrix_data: data.to_owned(),
row_num: rows as i32,
col_num: cols as i32
}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
matrix: self,
index: -1
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
matrix: self,
index: -self.col_num,
col_counter: 0
}
}
}
pub struct RowIter<'a, T> {
matrix: &'a Matrix<T>,
index: i32,
}
impl <'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index != self.matrix.col_num * self.matrix.row_num {
self.index += 1;
self.matrix.matrix_data.get(self.index as usize)
} else {
None
}
}
}
pub struct ColIter<'a, T> {
matrix: &'a Matrix<T>,
index: i32,
col_counter: i32
}
impl <'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index == (self.matrix.row_num * self.matrix.col_num - 1) {
None
} else {
self.index += self.matrix.col_num;
if self.index > (self.matrix.row_num * self.matrix.col_num - 1) {
self.col_counter += 1;
self.index = self.col_counter;
}
self.matrix.matrix_data.get(self.index as usize)
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1o1lod3/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.85s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Ивайло Димитров
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ивайло Димитров

#[derive(Debug)]
pub struct Matrix<T> {
height: usize,
width: usize,
elements: Vec<T>,
}
impl<T: Clone> Matrix<T> {
/// Конструира матрица с брой редове `rows` и брой колони `cols`. Данните би трябвало да бъдат
/// поне `rows * cols`, но няма да тестваме с масиви, които са твърде малки или твърде големи.
/// Ако искате да panic-нете при невалиден вход, ваш избор.
///
/// Данните ще са наредени в плосък масив по редове. Очаква се да държите ownership над тях,
/// така че си ги клонирайте и си ги наредете както ви е удобно.
///
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut elements: Vec<T> = Vec::new();
for var in data {
elements.push(var.clone());
}
Matrix{height: rows, width: cols, elements}
}
pub fn by_row(&self) -> RowIter<T> {
RowIter{matrix: self, current_index: 0}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter{matrix: self, current_row_index: 0, current_col_index: 0}
}
}
pub struct RowIter<'a, T> {
matrix: &'a Matrix<T>,
current_index: usize,
// каквото ви трябва
}
impl<'a, T: Clone> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current_index >= self.matrix.elements.len() {
None
}
else {
let ret = Some(&self.matrix.elements[self.current_index]);
self.current_index += 1;
ret
}
}
}
pub struct ColIter<'a, T> {
matrix: &'a Matrix<T>,
current_row_index: usize,
current_col_index: usize,
}
impl<'a, T: Clone> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
// update indexes if iterator has moved to next column
if self.current_row_index >= self.matrix.height {
self.current_row_index = 0;
self.current_col_index += 1;
}
if self.current_row_index >= self.matrix.height || self.current_col_index >= self.matrix.width {
None
}
else {
let ret = Some(&self.matrix.elements[self.matrix.width * self.current_row_index + self.current_col_index]);
self.current_row_index += 1;
ret
}
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-13ka1dr/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.43s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Марио Лалов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Марио Лалов

#[derive(Debug)]
pub struct Matrix<T> {
m_data: Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut matrix = Matrix::<T> { m_data: Vec::new() };
for i in 0..rows {
matrix.m_data.push(Vec::new());
for j in 0..cols {
matrix.m_data[i].push(data[i * cols + j].clone());
}
}
matrix
}
pub fn by_row(&self) -> RowIter<T> {
let mut iter = RowIter::<T> {
index_row: 0,
index_col: 0,
rows: Vec::new(),
};
for i in 0..self.m_data.len() {
iter.rows.push(Vec::new());
for j in 0..self.m_data[i].len() {
iter.rows[i].push(&self.m_data[i][j]);
}
}
iter
}
pub fn by_col(&self) -> ColIter<T> {
let mut iter = ColIter::<T> {
index_row: 0,
index_col: 0,
cols: Vec::new(),
};
//all rows have the same length so we can just use the length of the first one
for i in 0..self.m_data[0].len() {
iter.cols.push(Vec::new());
for j in 0..self.m_data.len() {
iter.cols[i].push(&self.m_data[j][i]);
}
}
iter
}
}
pub struct RowIter<'a, T> {
index_row: usize,
index_col: usize,
rows: Vec<Vec<&'a T>>,
}
impl<'a, T: Clone> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index_row > self.rows.len() - 1 {
return None;
}
//switch to new row
if self.index_col > self.rows[self.index_row].len() - 1 {
self.index_row += 1;
self.index_col = 1;
} else {
self.index_col += 1;
}
if self.index_row > self.rows.len() - 1 {
return None;
}
Some(&self.rows[self.index_row][self.index_col - 1])
}
}
pub struct ColIter<'a, T> {
index_row: usize,
index_col: usize,
cols: Vec<Vec<&'a T>>,
}
impl<'a, T: Clone> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.index_row > self.cols.len() - 1 {
return None;
}
//switch to new row
if self.index_col > self.cols[self.index_row].len() - 1 {
self.index_row += 1;
self.index_col = 1;
} else {
self.index_col += 1;
}
if self.index_row > self.cols.len() - 1 {
return None;
}
Some(&self.cols[self.index_row][self.index_col - 1])
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1jvy5hr/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.15s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Елизабет Колева
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Елизабет Колева

#[derive(Debug)]
pub struct Matrix<T> {
data: Vec<Vec<T>>,
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, input_data: &[T]) -> Self {
assert_eq!(cols*rows, input_data.len());
let mut data: Vec<Vec<T>> = vec![];
let mut curr_row: Vec<T> = vec![];
for row in 0_usize..rows {
for col in 0..cols {
curr_row.push(input_data[row*cols+col].clone());
}
data.push(curr_row);
curr_row = vec![];
}
Matrix { data }
}
pub fn by_row(&self) -> RowIter<T> {
let mut data: Vec<Vec<&T>> = vec![];
let mut curr_row: Vec<&T> = vec![];
let rows = self.data.len();
let cols = self.data[0].len();
for row in 0_usize..rows {
for col in 0..cols {
curr_row.push(&self.data[row][col]);
}
data.push(curr_row);
curr_row = vec![];
}
RowIter {
data,
ind_row: 0,
ind_col: 0,
}
}
pub fn by_col(&self) -> ColIter<T> {
let mut data: Vec<Vec<&T>> = vec![];
let mut curr_row: Vec<&T> = vec![];
let rows = self.data.len();
let cols = self.data[0].len();
for row in 0_usize..rows {
for col in 0..cols {
curr_row.push(&self.data[row][col]);
}
data.push(curr_row);
curr_row = vec![];
}
ColIter {
data,
ind_row: 0,
ind_col: 0,
}
}
}
pub struct RowIter<'a, T> {
data: Vec<Vec<&'a T>>,
ind_row: usize,
ind_col: usize,
}
pub struct ColIter<'a, T> {
data: Vec<Vec<&'a T>>,
ind_row: usize,
ind_col: usize,
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.ind_row == self.data.len() {
return None;
}
let result = self.data[self.ind_row][self.ind_col];
self.ind_col += 1;
if self.ind_col == self.data[0].len() {
self.ind_col = 0;
self.ind_row += 1;
}
Some(result)
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.ind_col == self.data[0].len() {
return None;
}
let result = self.data[self.ind_row][self.ind_col];
self.ind_row += 1;
if self.ind_row == self.data.len() {
self.ind_row = 0;
self.ind_col += 1;
}
Some(result)
}
}
#[cfg(test)]
mod tests {
use crate::{Matrix, ColIter, RowIter};
#[test]
fn test_iteration_0() {
let data = [1, 2,
3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
fn test_matrix_by_row_cyril() {
let mat = Matrix::new(2, 2, &['а', 'б', 'в', 'г']);
assert_eq!(mat.by_row().collect::<Vec<_>>(), vec![&'а', &'б', &'в', &'г']);
}
#[test]
fn test_matrix_by_row_emoj() {
let mat = Matrix::new(2, 2, &['😃', '😄', '😁', '😆']);
assert_eq!(mat.by_row().collect::<Vec<_>>(), vec![&'😃', &'😄', &'😁', &'😆']);
}
#[test]
#[should_panic]
fn test_bad_array_size() {
Matrix::new(2, 2, &[4, 3, 2, 1, 0]);
}
#[test]
fn test_matrix_by_row_next_none() {
let matry = Matrix::new(3, 2, &['а', 'б', 'в', 'г', 'д', 'е']);
let mut rows: RowIter<char> = matry.by_row();
assert_eq!(rows.next(), Some(&'а'));
assert_eq!(rows.next(), Some(&'б'));
assert_eq!(rows.next(), Some(&'в'));
assert_eq!(rows.next(), Some(&'г'));
assert_eq!(rows.next(), Some(&'д'));
assert_eq!(rows.next(), Some(&'е'));
assert_eq!(rows.next(), None);
assert_eq!(rows.next(), None);
}
#[test]
fn test_matrix_by_col_next_none() {
let matry = Matrix::new(3, 2, &['а', 'б', 'в', 'г', 'д', 'е']);
let mut cols: ColIter<char> = matry.by_col();
assert_eq!(cols.next(), Some(&'а'));
assert_eq!(cols.next(), Some(&'в'));
assert_eq!(cols.next(), Some(&'д'));
assert_eq!(cols.next(), Some(&'б'));
assert_eq!(cols.next(), Some(&'г'));
assert_eq!(cols.next(), Some(&'е'));
assert_eq!(cols.next(), None);
assert_eq!(cols.next(), None);
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-9lbhr7/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.99s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Петко Каменов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Петко Каменов

#[derive(Debug)]
pub struct Matrix<T> {
pub data : Vec<Vec<T>>,
pub rows : usize,
pub cols : usize
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
let mut arr = Matrix {
data: vec![vec![data[0].clone();cols];rows],
rows,
cols
};
let mut cur = 0;
for i in 0 .. rows {
for j in 0 .. cols {
arr.data[i][j] = (data[cur]).clone();
cur += 1;
}
}
arr
}
pub fn by_row(&self) -> RowIter<T> {
RowIter {
cur: Some(&self.data[0][0]),
data: & self.data,
rows : self.rows,
cols : self.cols,
i: 0,
j: 0,
first_call : true
}
}
pub fn by_col(&self) -> ColIter<T> {
ColIter {
cur: Some(&self.data[0][0]),
data: & self.data,
rows : self.rows,
cols : self.cols,
i: 0,
j: 0,
first_call : true
}
}
}
pub struct RowIter<'a,T> {
pub cur : Option<&'a T>,
data : &'a Vec<Vec<T>>,
rows : usize,
cols : usize,
i : usize,
j : usize,
first_call : bool
}
impl<'a,T: Clone> Iterator for RowIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.first_call {
self.first_call = false;
return self.cur;
}
self.j += 1;
if self.j >= self.cols {
self.j = 0;
self.i += 1;
}
if self.i >= self.rows {
return None;
}
self.cur = Some(&self.data[self.i][self.j]);
self.cur
}
}
pub struct ColIter<'a,T> {
pub cur : Option<&'a T>,
data : &'a Vec<Vec<T>>,
rows : usize,
cols : usize,
i : usize,
j : usize,
first_call : bool
}
impl<'a,T: Clone> Iterator for ColIter<'a,T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.first_call {
self.first_call = false;
return self.cur;
}
self.i += 1;
if self.i >= self.rows {
self.i = 0;
self.j += 1;
}
if self.j >= self.cols {
return None;
}
self.cur = Some(&self.data[self.i][self.j]);
self.cur
}
}
#[test]
fn test_iteration_0() {
let data = [1, 2,
3, 4];
let matrix = Matrix::new(2, 2, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &3, &2, &4]);
}
#[test]
fn test_iteration_1() {
let data = [1, 2,
3, 4,5,6,7,8,9];
let matrix = Matrix::new(3, 3, &data);
assert_eq!(matrix.by_row().collect::<Vec<_>>(), vec![&1, &2, &3, &4,&5,&6,&7,&8,&9]);
assert_eq!(matrix.by_col().collect::<Vec<_>>(), vec![&1, &4, &7, &2,&5,&8,&3,&6,&9]);
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-1y4gtpk/solution)
    Finished test [unoptimized + debuginfo] target(s) in 3.81s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Мартин Карликов
  • Некоректно
  • 2 успешни тест(а)
  • 1 неуспешни тест(а)
Мартин Карликов

#[derive(Debug)]
pub struct Matrix<T> {
cells : Vec<T>,
rows : usize,
cols : usize
}
impl<T: Clone> Matrix<T> {
pub fn new(rows: usize, cols: usize, data: &[T]) -> Self {
if rows * cols != data.len()
{
panic!("Data given for matrix does not correspond to dimensions!")
}
let mut cells = Vec::new();
for object in data
{
cells.push(object.clone())
}
Matrix { cells, rows, cols }
}
pub fn by_row(&self) -> RowIter<T> {
RowIter { index : 0, matrix : &self }
}
pub fn by_col(&self) -> ColIter<T> {
ColIter { col : 0, col_index : 0, matrix : &self }
}
}
pub struct RowIter<'a, T> {
index : usize,
matrix : &'a Matrix<T>
}
pub struct ColIter<'a, T> {
col : usize,
col_index : usize,
matrix : &'a Matrix<T>
}
impl<'a, T> Iterator for RowIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let current_index = self.index;
self.index += 1;
if current_index < self.matrix.cells.len()
{ Some(&self.matrix.cells[current_index]) }
else { None }
}
}
impl<'a, T> Iterator for ColIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.col >= self.matrix.cols
{
return None
}
let current_index = self.col + self.col_index;
if self.col_index < self.matrix.rows
{
self.col_index += self.matrix.cols;
}
else
{
self.col += 1;
self.col_index = 0;
}
if current_index < self.matrix.cells.len() { Some(&self.matrix.cells[current_index]) } else { None }
}
}
Compiling solution v0.1.0 (/tmp/d20211209-3212651-d5mohj/solution)
    Finished test [unoptimized + debuginfo] target(s) in 3.99s
     Running tests/solution_test.rs (target/debug/deps/solution_test-4c880d3f0adaac34)

running 3 tests
test solution_test::test_iteration_1 ... ok
test solution_test::test_iteration_2 ... ok
test solution_test::test_iteration_3 ... FAILED

failures:

---- solution_test::test_iteration_3 stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `["1", "4", "2", "5", "3", "6"]`,
 right: `["1", "4", "7", "2", "5", "8", "3", "6", "9"]`', tests/solution_test.rs:36:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_iteration_3

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

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