Advertisement
Guest User

Round_Robin_Variant

a guest
Sep 20th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.80 KB | None | 0 0
  1. local input = io.read("*a")
  2. local tasks = {}
  3. local stack = {}
  4. local processes = {}
  5. local processors = {}
  6. local n
  7. local processing = 0
  8.  
  9. for line in input:gmatch("[^\n]+") do
  10.     n = tonumber(line)
  11.     if not n then
  12.         local arrow_location = line:find("->")
  13.         local first_node = line:sub(1, arrow_location):match("%a+")
  14.         local second_node = line:sub(arrow_location):match("%a+")
  15.         tasks[first_node.."->"..second_node] = tonumber(line:match("%d+"))
  16.     end
  17. end
  18.  
  19. n = n or 1
  20. for i = 1, n do
  21.     processors["P"..i] = false
  22. end
  23.  
  24. for task in pairs(tasks) do
  25.     if task:match("START") then
  26.         processes[task] = true
  27.         table.insert(stack, task)
  28.     end
  29. end
  30.  
  31. while processing < n do
  32.     processing = 0
  33.     for i = 1, n do
  34.         local processor = "P"..i
  35.         local last_task = processors[processor]
  36.         if last_task then
  37.             tasks[last_task] = tasks[last_task] - 1
  38.             if tasks[last_task]  > 0 then
  39.                 table.insert(stack, 1, last_task)
  40.             else
  41.                 for task in pairs(tasks) do
  42.                     if last_task:reverse():match("%a+"):reverse() == task:match("%a+") then
  43.                         local can_add = true
  44.                         for other_task, time in pairs(tasks) do
  45.                             if other_task:reverse():match("%a+"):reverse() == task:match("%a+") and time > 0 then
  46.                                 can_add = false
  47.                             end
  48.                         end
  49.                         if can_add then
  50.                             table.insert(stack, task)
  51.                         end
  52.                     end
  53.                 end
  54.             end
  55.             processors[processor] = false
  56.         end
  57.         if #stack > 0 then
  58.             local task = table.remove(stack)
  59.             local second_node = task:reverse():match("%a+"):reverse()
  60.             io.write(processor, " processing task: ", second_node, "\n")
  61.             processors[processor] = task
  62.         else
  63.             processing = processing + 1
  64.             processors[processor] = false
  65.             io.write(processor, ": no task available to process at this time.", "\n")
  66.         end
  67.     end
  68. end
  69. io.write("\n", "Processing complete!", "\n\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement