AlgoMaster Logo
AlgoMasterThe Dining Philosophersmedium

The Dining Philosophers

medium

Five philosophers sit around a circular table. There is one fork between each pair of neighboring philosophers, and a philosopher can eat only while holding both adjacent forks.

The philosophers are numbered 0 through 4. For philosopher p:

  • The left fork is fork p.
  • The right fork is fork (p + 1) % 5.

The judge calls:

wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork)

The supplied callbacks record the philosopher's actions. Your implementation must invoke them so that:

  • A fork is held by at most one philosopher at a time.
  • A philosopher calls eat only while holding both adjacent forks.
  • Every picked-up fork is put down before wantsToEat returns.
  • All philosophers eventually finish without deadlock.

The judge creates one shared DiningPhilosophers instance and five threads. Each thread calls wantsToEat n times for its philosopher.

The judge also preloads the standard concurrency and callback APIs for each supported language. You do not need to add import, include, or using statements.

Example 1:

Input:

Output:

Explanation: This is one possible order in which the eat callbacks may complete. Other orders are valid if fork ownership is respected and every philosopher eats once.

Example 2:

Input:

Output:

Constraints

  • 1 <= n <= 60
  • There are exactly five philosophers and five forks.
  • The five philosopher threads share one DiningPhilosophers instance.
  • The supplied callbacks are thread-safe and return quickly.
Loading...

Input

n = 1

Output

[0, 2, 4, 1, 3]

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.