diff --git a/readme.md b/readme.md index ff7a266..dc4b834 100644 --- a/readme.md +++ b/readme.md @@ -9,7 +9,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom ## Challenge Completion -### 14 out of 100 public challenges completed. +### 15 out of 100 public challenges completed. - [x] 1 - [Multiples of 3 or 5](src/bin/1.rs) - [x] 2 - [Even Fibonacci numbers](src/bin/2.rs) @@ -25,7 +25,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom - [x] 12 - [Highly divisible triangular number](src/bin/12.rs) - [x] 13 - [Large sum](src/bin/13.rs) - [x] 14 - [Longest Collatz sequence](src/bin/14.rs) -- [ ] 15 - Lattice paths +- [x] 15 - [Lattice paths](src/bin/15.rs) - [ ] 16 - Power digit sum - [ ] 17 - Number letter counts - [ ] 18 - Maximum path sum I diff --git a/src/bin/15.rs b/src/bin/15.rs new file mode 100644 index 0000000..b005fe1 --- /dev/null +++ b/src/bin/15.rs @@ -0,0 +1,43 @@ +/* +Problem 15 - Lattice paths + +Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. +How many such routes are there through a 20×20 grid? +*/ + +fn binomial(n: usize, k: usize) -> Result { + if k > n { + return Err("k must be less than n!"); + } else if k == 0 { + return Ok(1); + } else if k > n / 2 { + return binomial(n, n - k); + } + + return Ok(n * binomial(n - 1, k - 1).unwrap() / k); +} + +fn count_lattice_paths(width: usize, height: usize) -> usize { + // All paths have width + height segments. k can either be width or height + // (symmetry of binomial coefficients) + if width != height { + return binomial(width + height, width).unwrap(); + } + + // (2n, n) + else { + let mut result: usize = 1; + + for i in 1..width { + result *= (width + i) / i; + } + + return result; + } +} + +fn main() { + let routes = count_lattice_paths(20, 20); + + println!("The amount of routes through a 20x20 grid is {routes}"); +}