华为2017实习生招聘笔试题-任务调度

2019-07-14 02:26发布

这里写图片描述
这里写图片描述
输入:[1.80.1.10]|[2.20.11.15]|[3.50.21.10]|[4.120.31.10]|[5.100.41.10]
输出:0.1|1.10|2.10|3.10|4.10|5.10|2.5|0.144 输入:[1.80.0.20]|[2.90.10.20]|[3.100.30.20]|[4.120.40.20]|[5.140.100.10]
输出:1.10|2.20|3.10|4.20|3.10|1.10|0.20|5.10|0.90 import java.util.*; class Task{ int id;//任务id int priority;//优先级 int start;//开始时间 int time;//持续时间 Task(int id,int priority,int start,int time){ this.id = id; this.priority = priority; this.start = start; this.time = time; } } public class Main {//线程调度 public static void main(String[] args) { Scanner sc = new Scanner(System.in); String in = sc.nextLine(); String[] tasks = in.split("\|"); Task[] taskList = new Task[5]; int index = 0; for(String task : tasks){ String[] content = task.substring(1,task.length() - 1).split("\."); int id = Integer.valueOf(content[0]); int priority = Integer.valueOf(content[1]); int start = Integer.valueOf(content[2]); int time = Integer.valueOf(content[3]); taskList[index++] = new Task(id,priority,start,time); } //排序tasklist,降序 sortTask(taskList); int[] cpu = new int[200]; //优先调度优先级高的任务 for(int i = 0; i < 200; i++){ for(Task task : taskList){ if(task.start <= i && task.time > 0){ task.time--; cpu[i] = task.id; break; } } } int start = -1; for(int end = 0; end < 199; end++){//输出结果 if(cpu[end] != cpu[end + 1]){ int time = end - start; start = end; System.out.print(cpu[end] + "." + time + "|"); } } int time = 199 - start;//输出最后一段 System.out.println(cpu[199] + "." + time); // for(int c : cpu){ // System.out.print(c + ","); // } } public static void sortTask(Task[] taskList){ for(int i = 0; i < taskList.length; i++){ for(int j = i; j > 0; j--){ if(taskList[j].priority > taskList[j - 1].priority){ Task temp = taskList[j]; taskList[j] = taskList[j - 1]; taskList[j - 1] = temp; } } } } }