diff options
| author | Federico Igne <git@federicoigne.com> | 2020-12-26 17:48:38 +0000 |
|---|---|---|
| committer | Federico Igne <git@federicoigne.com> | 2021-11-03 18:55:08 +0000 |
| commit | 02481656966b0a8dfc95cf3c22bcc049660ff7d4 (patch) | |
| tree | 8e39798fcaf27931d91c2088423fd4e97adcfc2d /rust/pascals-triangle/src | |
| parent | 4e2052c4d792540c2f742b2c2a081b11117ed41d (diff) | |
| download | exercism-02481656966b0a8dfc95cf3c22bcc049660ff7d4.tar.gz exercism-02481656966b0a8dfc95cf3c22bcc049660ff7d4.zip | |
Move Rust exercises in a subdirectory
Diffstat (limited to 'rust/pascals-triangle/src')
| -rw-r--r-- | rust/pascals-triangle/src/lib.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/rust/pascals-triangle/src/lib.rs b/rust/pascals-triangle/src/lib.rs new file mode 100644 index 0000000..7b2145b --- /dev/null +++ b/rust/pascals-triangle/src/lib.rs | |||
| @@ -0,0 +1,34 @@ | |||
| 1 | #[derive(Debug)] | ||
| 2 | pub struct PascalsTriangle { | ||
| 3 | rows: Vec<Vec<u32>>, | ||
| 4 | } | ||
| 5 | |||
| 6 | impl PascalsTriangle { | ||
| 7 | fn next_row(row: &[u32]) -> Vec<u32> { | ||
| 8 | let mut next = Vec::new(); | ||
| 9 | let last = row.iter().fold(0, |p, n| { | ||
| 10 | next.push(p + n); | ||
| 11 | *n | ||
| 12 | }); | ||
| 13 | next.push(last); | ||
| 14 | next | ||
| 15 | } | ||
| 16 | } | ||
| 17 | |||
| 18 | impl PascalsTriangle { | ||
| 19 | pub fn new(row_count: u32) -> Self { | ||
| 20 | let mut rows = Vec::new(); | ||
| 21 | if row_count > 0 { | ||
| 22 | rows.push(vec![1]); | ||
| 23 | (1..row_count).for_each(|i| { | ||
| 24 | let irow = Self::next_row(&rows[(i as usize) - 1]); | ||
| 25 | rows.push(irow); | ||
| 26 | }) | ||
| 27 | } | ||
| 28 | PascalsTriangle { rows } | ||
| 29 | } | ||
| 30 | |||
| 31 | pub fn rows(&self) -> Vec<Vec<u32>> { | ||
| 32 | self.rows.clone() | ||
| 33 | } | ||
| 34 | } | ||
