Drill

ProblemsTypeScript › patterns

How many ways across the yard

mediumpatternsRecursionGridsMathTypeScript

A forklift crosses a rectangular yard from the top-left bay to the bottom-right one, and may only ever drive right or down. Planning wants the number of distinct routes.

routesAcross(rows: int, columns: int) → int

Solve it in the editor →

Where you start

function routesAcross(rows: number, columns: number): number {
  
}

Worked examples

CallResult
routesAcross(3, 3)6
routesAcross(1, 1)1
routesAcross(2, 3)3
routesAcross(0, 5)0

Hint

The routes into a bay are the routes into the bay above plus the routes into the bay to its left. The top row and left column have exactly one each.

Reference solution in TypeScript
function routesAcross(rows: number, columns: number): number {
  if (rows <= 0 || columns <= 0) return 0;
  const ways: number[][] = [];
  for (let r = 0; r < rows; r += 1) ways.push(new Array(columns).fill(1));
  for (let r = 1; r < rows; r += 1) {
    for (let c = 1; c < columns; c += 1) {
      ways[r][c] = ways[r - 1][c] + ways[r][c - 1];
    }
  }
  return ways[rows - 1][columns - 1];
}

The same problem in another language

More patterns problems in TypeScript