Untitled

mail@pastecode.io avatar
unknown
java
a year ago
1.9 kB
2
Indexable
Never
import java.util.Arrays;

public class TaskCarousel {

    private int count = 0;

    private int executed = 0;
    private final Task[] carousel;

    public TaskCarousel(int capacity) {
        carousel = new Task[capacity];
    }

    public boolean addTask(Task task) {
        if (task == null ||  task.isFinished() ||  isFull()){
            return false;
        }
        else {
            carousel[count] = task;
            count++;
            return true;
        }
    }

    public boolean execute() {
        if (executed > carousel.length - 1){
            executed = executed - (carousel.length - 1);
        }
// Use a loop to find the next non-null and non-finished task to execute
// If none is found, return false
        for (int i = 0; i < carousel.length; i++) {
// Use modulo to wrap around the array in a circular order
            executed = (executed + 1) % carousel.length;
            if (carousel[executed] != null && !carousel[executed].isFinished()) {
// Execute the task and check if it is finished
                carousel[executed].execute();
                if (carousel[executed].isFinished()) {
// Set the finished task to null and decrement the count
                    carousel[executed] = null;
                    count--;
// Shift the remaining tasks to fill up the empty space
// This will preserve the execution order
                    for (int j = executed; j < count; j++) {
                        carousel[j] = carousel[j + 1];
                    }
// Set the last element to null to avoid duplication
                    carousel[count] = null;
// Decrement the executed index to account for the shift
                    executed--;
                }
// Return true after executing a task
                return true;
            }
        }
// Return false if no task was executed
        return false;
    }
}