Skip to content

Instantly share code, notes, and snippets.

@thunder775
Last active May 26, 2020 06:06
Show Gist options
  • Save thunder775/9a3b551b22566d6c3909399b65386668 to your computer and use it in GitHub Desktop.
Save thunder775/9a3b551b22566d6c3909399b65386668 to your computer and use it in GitHub Desktop.
function scheduler(array = [], n = 2) {
let taskCount = new Map();
array.forEach((char) => {
if (taskCount.get(char) !== undefined) {
taskCount.set(char, taskCount.get(char) + 1)
} else {
taskCount.set(char, 1)
}
});
let sortedFrequencies = [...taskCount.entries()].sort((a, b) => b[1] - a[1]);
let scheduledTasks = [];
let counter = 0;
while (taskCount.size !== 0) {
let task = sortedFrequencies.find(([char, count]) => canBeInserted(scheduledTasks, char));
if (task === undefined) {
scheduledTasks.push(null)
} else {
let [char, count] = task;
scheduledTasks.push(char);
count-1===0?taskCount.delete(char):taskCount.set(char,count-1);
}
counter++;
if (scheduledTasks.length === n + 1) scheduledTasks.shift();
sortedFrequencies = [...taskCount.entries()].sort((a, b) => b[1] - a[1]);
}
return counter;
}
function canBeInserted(list = [], element = '') {
return list.indexOf(element) === -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment