Skip to content

Latest commit

 

History

History
65 lines (51 loc) · 2.46 KB

06-5-2023.md

File metadata and controls

65 lines (51 loc) · 2.46 KB

Algorithms: Coding Puzzles

Title:

Question 1: Who’s the fastest runner?

Language:

Javascript

Algorithm:

  1. Initialize an empty list to hold the runners' distances.
  2. For each runner: a. Initialize a variable distance to 0 to keep track of their total distance covered. b. Initialize a variable time to 0 to keep track of the current time. c. While the current time is less than the total race time: i. If the runner is resting, add the rest time to the current time and continue. ii. If the runner is running, calculate the distance covered based on their speed and the remaining time they can run. iii. Add the distance covered to the total distance. iv. Add the running time to the current time. v. If the runner has reached the end of their running time, switch to rest mode. vi. If the race time has elapsed, break out of the loop. d. Append the total distance covered by the runner to the list of distances.
  3. Find the maximum distance from the list of distances.
  4. Find the index of the maximum distance from the list of distances.
  5. Use the index to retrieve the corresponding runner's name from the original list of runners.
  6. Return the name of the winner and the distance.

Code:

const runners = [
  { name: 'John', speed: 10, runDuration: 6, restDuration: 20 },
  { name: 'James', speed: 8, runDuration: 8, restDuration: 25 },
  { name: 'Jenna', speed: 12, runDuration: 5, restDuration: 16 },
  { name: 'Josh', speed: 7, runDuration: 7, restDuration: 23 },
  { name: 'Jacob', speed: 9, runDuration: 4, restDuration: 32 },
  { name: 'Jerry', speed: 5, runDuration: 9, restDuration: 18 }
];

const raceDuration = 1234;

// Calculate the distance traveled by each runner
const distances = runners.map(runner => {
  let distance = 0;
  let time = 0;
  while (time < raceDuration) {
    distance += Math.min(runner.speed * runner.runDuration, (raceDuration - time) * runner.speed);
    time += runner.runDuration + runner.restDuration;
  }
  return { name: runner.name, distance };
});

// Find the winner's name based on the distance traveled
const winner = distances.reduce((prev, current) => {
  return (prev.distance > current.distance) ? prev : current;
});

console.log(`The winner is ${winner.name} with a distance of ${winner.distance} metres.`);
  

Solution:

The winner is Jenna with a distance of 3540 metres.