Round Robin
话说有一堆进程,有到达时间arriveTime[],还有执行时间executeTime[]。
我们这里有一个q,就是最大执行时间片。
需要我们模拟一下Round Robin这种调度方法。
例子: 【0,1,4】 【5,2,3】 q=3. 输出的是average wait time 2.3333333
例子的解释又臭又长。
import java.util.LinkedList;
import java.util.Queue;
class Process {
    int arrTime;
    int exeTime;
    Process(int arr, int exe) {
        arrTime = arr;
        exeTime = exe;
    }
}
public class RoundRobin {
    public static void main(String[] args) {
        int[] Atime = {0,1,4};
        int[] Etime = {5,2,3};
        System.out.println(Solution(Atime, Etime, 3));
    }
    
    
    public static float Solution(int[] Atime, int[] Etime, int q) {
        
        if (Atime == null || Etime == null || Atime.length != Etime.length) {
            return 0;
        }
        int length = Atime.length;
        
        Queue<Process> queue = new LinkedList<Process>();
        int curTime = 0, totalWaitTime = 0, index = 0;
        
        while (!queue.isEmpty() || index < length) {
            if (queue.isEmpty()) {
                queue.offer(new Process(Atime[index], Etime[index]));
                curTime = Atime[index++];
            } else {
                
                Process cur = queue.poll();
                totalWaitTime += curTime - cur.arrTime;
                curTime += Math.min(q, cur.exeTime);
                
                while (index < length && Atime[index] <= curTime) {
                    queue.offer(new Process(Atime[index], Etime[index]));
                    index++;
                }
                
                if (cur.exeTime > q) {
                    queue.offer(new Process(curTime, cur.exeTime - q));
                }
            }
        }
        return (float) totalWaitTime / length;
    }
}