Daily Coding Sixty Two

Dearest Corinthia, twas’t been a fortnite ‘til eyes lain upon. I yurn once more for to gaze upon your coding solution to a rando email. Ever yours, Dwayne Wyatt Evernly VI, Esq.

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
/*
There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.

For example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:

Right, then down
Down, then right
Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.
*/

function countWays(N, M) {
// create a zero'd out 2D array 'matrix' with dimensions N x M
const matrix = Array.from({ length: N }, () => Array(M).fill(0));

matrix[0][0] = 1;

// fill the Matrix...*whoa*
for (let i = 0; i < N; i++) {
for (let j = 0; j < M; j++) {
// If moving right is possible
if (j > 0) {
matrix[i][j] += matrix[i][j - 1];
}
// If moving down is possible
if (i > 0) {
matrix[i][j] += matrix[i - 1][j];
}
}
}

// the bottom-right corner will have the number of ways to reach it
return matrix[N - 1][M - 1];
}

Running this a few times netted:

1
2
3
4
console.log(countWays(2, 2)); // Output: 2
console.log(countWays(5, 5)); // Output: 70
console.log(countWays(10,3)); // Output: 55
console.log(countWays(18,10)); // Output 3124550