File tree Expand file tree Collapse file tree
exercises/practice/matrix/src Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11pub struct Matrix {
2- // Implement your Matrix struct
2+ elements : Vec < u32 > ,
3+ nrow : usize ,
4+ ncol : usize ,
35}
46
57impl Matrix {
68 pub fn new ( input : & str ) -> Self {
7- todo ! ( "Create new method to store the {input}" )
9+ let lines = input. split ( "\n " ) ;
10+ let nrow = lines. clone ( ) . count ( ) ;
11+ let elements: Vec < u32 > = lines
12+ . flat_map ( |line| line. split ( ' ' ) . map ( |el| el. parse :: < u32 > ( ) . unwrap ( ) ) )
13+ . collect ( ) ;
14+ let ncol = elements. clone ( ) . len ( ) / nrow;
15+
16+ println ! ( "nrow {nrow}, elements {elements:?}, ncol {ncol}" ) ;
17+ Self {
18+ nrow,
19+ elements,
20+ ncol,
21+ }
822 }
923
1024 pub fn row ( & self , row_no : usize ) -> Option < Vec < u32 > > {
11- todo ! ( "Return the row at {row_no} (1-indexed) or None if the number is invalid" )
25+ if row_no > self . nrow {
26+ return None ;
27+ }
28+
29+ self . elements
30+ . get ( ( ( row_no - 1 ) * self . ncol ) ..( row_no * self . ncol ) )
31+ . map ( |s| s. to_vec ( ) )
1232 }
1333
1434 pub fn column ( & self , col_no : usize ) -> Option < Vec < u32 > > {
15- todo ! ( "Return the column at {col_no} (1-indexed) or None if the number is invalid" )
35+ if col_no > self . ncol {
36+ return None ;
37+ }
38+
39+ ( ( col_no - 1 ) ..( self . nrow * self . ncol ) )
40+ . step_by ( self . ncol )
41+ . map ( |i| self . elements . get ( i) . copied ( ) )
42+ . collect ( )
1643 }
1744}
You can’t perform that action at this time.
0 commit comments