Skip to content

Instantly share code, notes, and snippets.

@Tomotoes
Created September 25, 2020 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tomotoes/bc6318b175c943723cb057d0c783dbfc to your computer and use it in GitHub Desktop.
Save Tomotoes/bc6318b175c943723cb057d0c783dbfc to your computer and use it in GitHub Desktop.
leastWorkTime
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