DEV Community

Discussion on: Daily Challenge #162 - Taxi Dispatching

Collapse
 
sarah4594 profile image
sarah4594

My solution in Typescript

export const min_num_taxis = (requests: number[][]): number => {
  const taxis: number[] = []
  // sort by dropoff time
  requests.sort((reqA, reqB) => reqA[1] - reqB[1])
  requests.forEach(request => {
    const [pickup, dropoff] = request
    let foundTaxi = false
    for (let taxi = 0; taxi <= taxis.length; taxi++) {
      if (pickup > taxis[taxi]) {
        foundTaxi = true
        taxis[taxi] = dropoff
      }
    }
    if (!foundTaxi) {
      taxis.push(dropoff)
    }
  })
  return taxis.length
}

and tests

import { min_num_taxis } from '.'

describe('min_num_taxis', () => {
  it('should return the number of taxis needed per request', () => {
    expect(min_num_taxis([[1, 4]])).toBe(1)
    expect(min_num_taxis([[5, 9], [1, 4]])).toBe(1)
    expect(min_num_taxis([[1, 4], [2, 9], [3, 6], [5, 8] ])).toBe(3)
  })
})