feat(problem): 15 - lattice paths
This commit is contained in:
parent
264a0c093f
commit
51c4dd6c65
2 changed files with 45 additions and 2 deletions
|
@ -9,7 +9,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom
|
|||
|
||||
## Challenge Completion
|
||||
|
||||
### <!-- completed -->14<!-- completed --> out of 100 public challenges completed.
|
||||
### <!-- completed -->15<!-- completed --> 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
|
||||
|
|
43
src/bin/15.rs
Normal file
43
src/bin/15.rs
Normal file
|
@ -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<usize, &'static str> {
|
||||
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}");
|
||||
}
|
Loading…
Reference in a new issue