Open In App

Task Allocation to Game Slots

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n tasks, each represented by two arrays: start_time and duration. The start_time array represents the start time of each task, and the duration array represents the duration of each task. Your goal is to design an allocation strategy for these tasks to maximize their chances of being processed. The tasks need to be assigned to available game slots or processing units. If there are no available game slots at the starting time of a task, the task is lost. Your task is to determine the allocation of tasks to game slots, and if a task cannot be allocated, assign -1 to it.

Examples:

Input: n = 3, start_time = {2, 4, 1, 8, 9}, and duration = {7, 9, 2, 4, 5}
Output: 1,2,1,3,2
Explanation: Since three slots are given that is 3 that i.e.{1,2,3}
Task 3 (start time: 1, duration: 2) is assigned to Game Slot 1 (since it’s available at time 1).
Task 1 (start time: 2, duration: 7) is assigned to Game Slot 2 (available at time 2).
Task 2 (start time: 4, duration: 4) is assigned to Game Slot 1 (available at time 1).
Task 4 (start time: 8, duration: 9) is assigned to Game Slot 3 (available at time 3).
Task 5 (start time: 9, duration: 5) is assigned to Game Slot 2 (available at time 2).

Input: n = 4, start_time = {3, 5, 1, 6, 8}, and duration = {9, 2, 10, 4, 5}
Output: 1 2 3 4 3

Approach: The problem can be solved using the following approach:

The approach is to efficiently assign tasks with start times and durations to available game slots in a way that maximizes processing, minimizing the chances of task loss by sorting tasks by start times, iterating through them, and assigning each task to the first available game slot or marking it with -1 if no slot is available at its start time.

Steps to solve the problem:

  • Create a vector to store slot assignments for each task.
  • Create a vector to store slot availability times, initializing all slots as available at time 0.
  • Create a vector of task requests containing start times, durations, and original indices.
  • Sort the task requests based on their start times.
  • Iterate through the sorted task requests:
    • For each task request, get its start time, duration, and original index.
    • Initialize a Boolean variable to track if the task is assigned.
    • Find the first available slot or the slot with the lowest availability time.
    • If an available slot is found, assign the task to the slot, update the slot’s availability time, and mark the task as assigned.
    • If no slot is available for the task at its start time, mark it with -1.
  • Return the vector of slot assignments.

Below is the implementation of the approach:

C++




// C++ code for the above approach:
#include <algorithm>
#include <iostream>
#include <vector>
 
using namespace std;
 
// Define a function to allocate
// tasks to game slots.
vector<int> allocateTasksToSlots(int numSlots,
                                vector<int> startTimes,
                                vector<int> durations)
{
 
    // Vector to store slot assignments
    // for each task.
    vector<int> slotAssignments;
 
    // Initialize all slots to be
    // available at time 0.
    vector<int> slotAvailability(numSlots, -1);
 
    // Create a vector of task requests
    // containing start times, durations,
    // and original indices.
    vector<pair<pair<int, int>, int> > taskRequests;
    for (int i = 0; i < startTimes.size(); i++) {
        taskRequests.push_back(
            { { startTimes[i], durations[i] }, i });
    }
 
    // Sort task requests based on start times.
    sort(taskRequests.begin(), taskRequests.end());
 
    // Iterate through the sorted task requests.
    for (const auto& request : taskRequests) {
        int taskStartTime = request.first.first;
        int taskDuration = request.first.second;
        int taskIndex = request.second;
 
        bool taskAssigned = false;
 
        // Find the first available slot or the
        // slot with the lowest availability time.
        for (int slot = 0; slot < numSlots; slot++) {
            if (slotAvailability[slot] <= taskStartTime) {
 
                // Assign the task to the slot.
                slotAssignments.push_back(
                    slot + 1); // Slot numbers start from 1.
                slotAvailability[slot]
                    = taskStartTime + taskDuration;
                taskAssigned = true;
                break;
            }
        }
 
        // If no slot is available for the task,
        // mark it with -1.
        if (!taskAssigned) {
            slotAssignments.push_back(-1);
        }
    }
 
    return slotAssignments;
}
 
// Drivers code
int main()
{
    int numSlots = 4;
    vector<int> startTimes = { 2, 4, 1, 8, 9 };
    vector<int> durations = { 7, 9, 2, 4, 5 };
 
    vector<int> slotAssignments = allocateTasksToSlots(
        numSlots, startTimes, durations);
 
    // Print the slot assignments for each task.
    for (int i : slotAssignments) {
        cout << i << " ";
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class TaskScheduler {
 
    // Define a function to allocate tasks to game slots.
    public static List<Integer> allocateTasksToSlots(int numSlots, List<Integer> startTimes, List<Integer> durations) {
 
        // List to store slot assignments for each task.
        List<Integer> slotAssignments = new ArrayList<>();
 
        // Initialize all slots to be available at time 0.
        List<Integer> slotAvailability = new ArrayList<>(Collections.nCopies(numSlots, -1));
 
        // Create a list of task requests containing start times, durations, and original indices.
        List<Triplet> taskRequests = new ArrayList<>();
        for (int i = 0; i < startTimes.size(); i++) {
            taskRequests.add(new Triplet(startTimes.get(i), durations.get(i), i));
        }
 
        // Sort task requests based on start times.
        Collections.sort(taskRequests);
 
        // Iterate through the sorted task requests.
        for (Triplet request : taskRequests) {
            int taskStartTime = request.getStartTime();
            int taskDuration = request.getDuration();
            int taskIndex = request.getIndex();
 
            boolean taskAssigned = false;
 
            // Find the first available slot or the slot with the lowest availability time.
            for (int slot = 0; slot < numSlots; slot++) {
                if (slotAvailability.get(slot) <= taskStartTime) {
 
                    // Assign the task to the slot.
                    slotAssignments.add(slot + 1); // Slot numbers start from 1.
                    slotAvailability.set(slot, taskStartTime + taskDuration);
                    taskAssigned = true;
                    break;
                }
            }
 
            // If no slot is available for the task, mark it with -1.
            if (!taskAssigned) {
                slotAssignments.add(-1);
            }
        }
 
        return slotAssignments;
    }
 
    // Driver code
    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);
 
        // Print the slot assignments for each task.
        for (int i : slotAssignments) {
            System.out.print(i + " ");
        }
    }
 
    // Helper class to represent a task request
    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);
        }
    }
}


Python3




def allocate_tasks_to_slots(num_slots, start_times, durations):
    # List to store slot assignments for each task.
    slot_assignments = []
 
    # Initialize all slots to be available at time 0.
    slot_availability = [-1] * num_slots
 
    # Create a list of task requests containing start times, durations, and original indices.
    task_requests = [((start_times[i], durations[i]), i) for i in range(len(start_times))]
 
    # Sort task requests based on start times.
    task_requests.sort()
 
    # Iterate through the sorted task requests.
    for request in task_requests:
        task_start_time, task_duration = request[0]
        task_index = request[1]
 
        task_assigned = False
 
        # Find the first available slot or the slot with the lowest availability time.
        for slot in range(num_slots):
            if slot_availability[slot] <= task_start_time:
                # Assign the task to the slot.
                slot_assignments.append(slot + 1# Slot numbers start from 1.
                slot_availability[slot] = task_start_time + task_duration
                task_assigned = True
                break
 
        # If no slot is available for the task, mark it with -1.
        if not task_assigned:
            slot_assignments.append(-1)
 
    return slot_assignments
 
 
# Driver code
if __name__ == "__main__":
    num_slots = 4
    start_times = [2, 4, 1, 8, 9]
    durations = [7, 9, 2, 4, 5]
 
    slot_assignments = allocate_tasks_to_slots(num_slots, start_times, durations)
 
    # Print the slot assignments for each task.
    for i in slot_assignments:
        print(i, end=" ")
#This code is contributed by Rohit Singh


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Define a function to allocate tasks to game slots.
    static List<int> AllocateTasksToSlots
      (int numSlots, List<int> startTimes, List<int> durations)
    {
        // List to store slot assignments for each task.
        List<int> slotAssignments = new List<int>();
 
        // Initialize all slots to be available at time 0.
        List<int> slotAvailability = Enumerable.Repeat(-1, numSlots).ToList();
 
        // Create a list of task requests containing start times, durations, and original indices.
        List<Tuple<Tuple<int, int>, int>> taskRequests = new List<Tuple<Tuple<int, int>, int>>();
        for (int i = 0; i < startTimes.Count; i++)
        {
            taskRequests.Add
              (new Tuple<Tuple<int, int>, int>
               (new Tuple<int, int>(startTimes[i], durations[i]), i));
        }
 
        // Sort task requests based on start times.
        taskRequests = taskRequests.OrderBy(t => t.Item1.Item1).ToList();
 
        // Iterate through the sorted task requests.
        foreach (var request in taskRequests)
        {
            int taskStartTime = request.Item1.Item1;
            int taskDuration = request.Item1.Item2;
            int taskIndex = request.Item2;
 
            bool taskAssigned = false;
 
            // Find the first available slot or the slot with the lowest availability time.
            for (int slot = 0; slot < numSlots; slot++)
            {
                if (slotAvailability[slot] <= taskStartTime)
                {
                    // Assign the task to the slot.
                    slotAssignments.Add(slot + 1); // Slot numbers start from 1.
                    slotAvailability[slot] = taskStartTime + taskDuration;
                    taskAssigned = true;
                    break;
                }
            }
 
            // If no slot is available for the task, mark it with -1.
            if (!taskAssigned)
            {
                slotAssignments.Add(-1);
            }
        }
 
        return slotAssignments;
    }
 
    // Driver code
    static void Main()
    {
        int numSlots = 4;
        List<int> startTimes = new List<int> { 2, 4, 1, 8, 9 };
        List<int> durations = new List<int> { 7, 9, 2, 4, 5 };
 
        List<int> slotAssignments = AllocateTasksToSlots(numSlots, startTimes, durations);
 
        // Print the slot assignments for each task.
        foreach (int i in slotAssignments)
        {
            Console.Write(i + " ");
        }
    }
}


Javascript




function allocateTasksToSlots(numSlots, startTimes, durations) {
    // Array to store slot assignments for each task.
    const slotAssignments = [];
 
    // Initialize all slots to be available at time 0.
    const slotAvailability = Array(numSlots).fill(-1);
 
    // Create a list of task requests containing start times,
    // durations, and original indices.
    const taskRequests = startTimes.map((startTime, i) =>
                        ({ startTime, duration: durations[i], originalIndex: i }));
 
    // Sort task requests based on start times.
    taskRequests.sort((a, b) => a.startTime - b.startTime);
 
    // Iterate through the sorted task requests.
    for (const request of taskRequests) {
        const taskStartTime = request.startTime;
        const taskDuration = request.duration;
        const taskIndex = request.originalIndex;
 
        let taskAssigned = false;
 
        // Find the first available slot or the slot with
        // the lowest availability time.
        for (let slot = 0; slot < numSlots; slot++) {
            if (slotAvailability[slot] <= taskStartTime) {
                // Assign the task to the slot.
                slotAssignments.push(slot + 1); // Slot numbers start from 1.
                slotAvailability[slot] = taskStartTime + taskDuration;
                taskAssigned = true;
                break;
            }
        }
 
        // If no slot is available for the task, mark it with -1.
        if (!taskAssigned) {
            slotAssignments.push(-1);
        }
    }
 
    return slotAssignments;
}
 
// Driver code
const numSlots = 4;
const startTimes = [2, 4, 1, 8, 9];
const durations = [7, 9, 2, 4, 5];
 
const slotAssignments = allocateTasksToSlots(
                          numSlots, startTimes, durations);
 
// Print the slot assignments for each task.
console.log(slotAssignments.join(" "));


Output

1 2 1 3 2 








Time Complexity: O(n *numTasks), where n is the number of task requests.
Auxiliary Space: O(numTasks).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads