Created
September 25, 2020 10:30
-
-
Save SimonAKing/bc6318b175c943723cb057d0c783dbfc to your computer and use it in GitHub Desktop.
leastWorkTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const patchTasksByTimeout = (task, tasks, timeout) => { | |
return tasks.reduce((a, t) => { | |
if (t.value === task.value) { | |
t.timeout = timeout | |
} else { | |
t.timeout = Math.max(0, t.timeout - 1) | |
} | |
return [...a, t] | |
}, []) | |
} | |
const getBestTask = tasks => { | |
return tasks.reduce(({ max, result, hash }, task) => { | |
const { value } = task | |
if (!hash[value]) { | |
hash[value] = 0 | |
} | |
hash[value]++ | |
if (max < hash[value]) { | |
max = hash[value] | |
result = task | |
} | |
return { max, result, hash } | |
}, { max: 0, result: null, hash: {} }).result | |
} | |
function leastWorkTime(_tasks, n) { | |
let tasks = _tasks.map(v => ({ value: v, timeout: 0 })) | |
let seconds = 0 | |
while (tasks.length) { | |
const availableTasks = tasks.filter(({ timeout }) => timeout === 0) | |
if (availableTasks && availableTasks.length) { | |
const task = getBestTask(availableTasks) | |
tasks = patchTasksByTimeout(task, tasks.filter(t => t !== task), n) | |
} else { | |
tasks = patchTasksByTimeout({ value: NaN }, tasks, n) | |
} | |
seconds++ | |
} | |
return seconds | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment