import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
public
class
TaskScheduler {
public
static
List<Integer> allocateTasksToSlots(
int
numSlots, List<Integer> startTimes, List<Integer> durations) {
List<Integer> slotAssignments =
new
ArrayList<>();
List<Integer> slotAvailability =
new
ArrayList<>(Collections.nCopies(numSlots, -
1
));
List<Triplet> taskRequests =
new
ArrayList<>();
for
(
int
i =
0
; i < startTimes.size(); i++) {
taskRequests.add(
new
Triplet(startTimes.get(i), durations.get(i), i));
}
Collections.sort(taskRequests);
for
(Triplet request : taskRequests) {
int
taskStartTime = request.getStartTime();
int
taskDuration = request.getDuration();
int
taskIndex = request.getIndex();
boolean
taskAssigned =
false
;
for
(
int
slot =
0
; slot < numSlots; slot++) {
if
(slotAvailability.get(slot) <= taskStartTime) {
slotAssignments.add(slot +
1
);
slotAvailability.set(slot, taskStartTime + taskDuration);
taskAssigned =
true
;
break
;
}
}
if
(!taskAssigned) {
slotAssignments.add(-
1
);
}
}
return
slotAssignments;
}
public
static
void
main(String[] args) {
int
numSlots =
4
;
List<Integer> startTimes = List.of(
2
,
4
,
1
,
8
,
9
);
List<Integer> durations = List.of(
7
,
9
,
2
,
4
,
5
);
List<Integer> slotAssignments = allocateTasksToSlots(numSlots, startTimes, durations);
for
(
int
i : slotAssignments) {
System.out.print(i +
" "
);
}
}
static
class
Triplet
implements
Comparable<Triplet> {
private
int
startTime;
private
int
duration;
private
int
index;
public
Triplet(
int
startTime,
int
duration,
int
index) {
this
.startTime = startTime;
this
.duration = duration;
this
.index = index;
}
public
int
getStartTime() {
return
startTime;
}
public
int
getDuration() {
return
duration;
}
public
int
getIndex() {
return
index;
}
@Override
public
int
compareTo(Triplet other) {
return
Integer.compare(
this
.startTime, other.startTime);
}
}
}