Created
July 16, 2017 07:48
-
-
Save jianminchen/00fe1ef58dc85a6608cf2284bc2cc898 to your computer and use it in GitHub Desktop.
Round robin - study code written in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Solution { | |
static class Task | |
{ | |
int arrive; | |
int remain; | |
public Task(int arrive, int remain) | |
{ | |
this.arrive = arrive; | |
this.remain = remain; | |
} | |
} | |
public static double roundRobin(int[] arriveTime, int[] runTime, int slot) | |
{ | |
Queue<Task> queue = new LinkedList<>(); | |
int i = 0, t = 0, wait = 0; | |
while(i < arriveTime.length || !queue.isEmpty()) | |
{ | |
if(!queue.isEmpty()) | |
{ | |
Task peek = queue.poll(); | |
wait += (t - peek.arrive); | |
if(peek.remain > slot) | |
{ | |
t += slot; | |
peek.remain -= slot; | |
peek.arrive = t; | |
} | |
else | |
{ | |
t += peek.remain; | |
peek.remain = 0; | |
peek.arrive = t; | |
} | |
while(i < arriveTime.length && arriveTime[i] <= t) | |
{ | |
queue.offer(new Task(arriveTime[i], runTime[i])); | |
i++; | |
} | |
if(peek.remain != 0) queue.offer(peek); | |
} | |
else | |
{ | |
queue.offer(new Task(arriveTime[i], runTime[i])); | |
t = arriveTime[i]; | |
i++; | |
} | |
} | |
return (wait + 0.0) / arriveTime.length; | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
int[] arriveTime = {0, 1, 3, 9}; | |
int[] runTime = {2, 1, 7, 5}; | |
System.out.println(roundRobin(arriveTime, runTime, 2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment