Advertisement
Cool_Dalek

Dinig philosophers

May 9th, 2023
2,314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.50 KB | None | 0 0
  1. import cats.*
  2. import cats.syntax.all.*
  3. import cats.effect.*
  4. import cats.effect.std.*
  5.  
  6. import scala.collection.mutable
  7.  
  8. object Philosophers extends IOApp.Simple:
  9.  
  10.   val run: IO[Unit] = dining(5)
  11.  
  12.   case class Philosopher(self: Int, leftStick: Int, rightStick: Int)
  13.   given Show[Vector[Philosopher]] = _.map(_.self).mkString("(", ",", ")")
  14.  
  15.   def dining(n: Int): IO[Unit] =
  16.    
  17.     def schedule(queue: Vector[Philosopher]): (Vector[Philosopher], Vector[Philosopher]) =
  18.       val eating = Vector.newBuilder[Philosopher]
  19.       val blocked = Vector.newBuilder[Philosopher]
  20.       val claimed = mutable.Set.empty[Int]
  21.  
  22.       queue.foreach { p =>
  23.         val isBlocked = claimed.contains(p.leftStick) || claimed.contains(p.rightStick)
  24.         if isBlocked then
  25.           blocked.addOne(p)
  26.         else
  27.           eating.addOne(p)
  28.           claimed.addOne(p.leftStick)
  29.           claimed.addOne(p.rightStick)
  30.         end if
  31.       }
  32.  
  33.       val active = eating.result()
  34.       val updated = blocked.addAll(active).result()
  35.       (active, updated)
  36.     end schedule
  37.  
  38.     def loop(philosophers: Vector[Philosopher]): IO[Unit] =
  39.       val (active, queue) = schedule(philosophers)
  40.       IO.println(active) >> loop(queue)
  41.  
  42.     val philosophers = Vector.tabulate(n) { self =>
  43.       val left =
  44.         val candidate = self - 1
  45.         if candidate < 0
  46.         then n - 1
  47.         else candidate
  48.       end left
  49.       Philosopher(self, left, self)
  50.     }
  51.     loop(philosophers)
  52.   end dining
  53.  
  54. end Philosophers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement