中级农民
- 积分
- 100
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-20
- 最后登录
- 1970-1-1
|
辛辛苦苦写的代码为何PO不上来……
- public class RoundRobin
- {
- public static void main(String[] args)
- {
- // int[] a = { 0, 2, 4, 5 }, b = { 7, 4, 1, 4 };
- // int[] a = { 0, 1, 3, 9 }, b = { 2, 1, 7, 5 };
- int[] a = { 0, 1, 4 }, b = { 5, 2, 3 };
- System.out.println(new RoundRobin().waitingTime(a, b, 3));
- }
- public float waitingTime(int[] requestTimes, int[] executionTimes, int interval)
- {
- if (null == requestTimes || 0 == requestTimes.length || null == executionTimes || 0 == executionTimes.length)
- {
- return 0;
- }
- int[] workingTimes = new int[executionTimes.length], lastActiveEndTime = new int[executionTimes.length];
- for (int i = 0; i < executionTimes.length; i++)
- {
- workingTimes[i] = executionTimes[i];
- lastActiveEndTime[i] = requestTimes[i];
- }
- // current work index
- int curIndex = 0, curTime = 0, waitingTime = 0;
- boolean allFinished = true;
- while (true)
- {
- curIndex = (curIndex + 1) % requestTimes.length;
- if (0 == workingTimes[curIndex])
- {
- allFinished = true;
- for (int i = 0; i < workingTimes.length; i++)
- {
- if (0 != workingTimes[i])
- {
- allFinished = false;
- break;
- }
- }
- if (allFinished)
- {
- break;
- }
- else
- {
- continue;
- }
- }
- // must has received the job in order to start
- if (curTime >= requestTimes[curIndex])
- {
- if (0 <= workingTimes[curIndex] - interval)
- {
- curTime += interval;
- lastActiveEndTime[curIndex] = curTime;
- waitingTime += checkWaitingTime(requestTimes, workingTimes, lastActiveEndTime, curTime, curIndex);
- workingTimes[curIndex] -= interval;
- }
- else
- {
- curTime += workingTimes[curIndex];
- lastActiveEndTime[curIndex] = curTime;
- waitingTime += checkWaitingTime(requestTimes, workingTimes, lastActiveEndTime, curTime, curIndex);
- workingTimes[curIndex] = 0;
- }
- }
- }
- return ((float) waitingTime) / requestTimes.length;
- }
- private int checkWaitingTime(int[] requestTimes, int[] workingTimes, int[] lastActiveEndTime, int curTime,
- int curIndex)
- {
- int waitingTime = 0;
- for (int i = 0; i < requestTimes.length; i++)
- {
- if (i != curIndex && curTime >= requestTimes[i] && 0 < workingTimes[i])
- {
- waitingTime += (curTime - lastActiveEndTime[i]);
- lastActiveEndTime[i] = curTime;
- }
- }
- return waitingTime;
- }
- }
复制代码
补充内容 (2017-1-17 09:26):
在计算每一次等待时间的时候 用当前时间减去上次更新的时间就可以 直接减去当前工作时长是不对的
可以用下面情况
[0, 1], [3, 2], q = 3
直接用waiting += q的话
waiting time会是3不是1 |
|