Created
December 18, 2018 15:13
-
-
Save tevko/20f8fc446d219f4714517aab19c5dd71 to your computer and use it in GitHub Desktop.
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
Let's say I have an array of 8 objects. Each object represents a task which can be completed multiple times. | |
In this case, the goal is to complete each task as many times as possible, until the allotted time per task is up | |
and I must move on to the next task. Let's also say that I have a total of ten minutes (600 seconds) to spend on | |
all tasks combined. Using javascript, how can I assign a random number of seconds (no less than 45, assuming each | |
task takes a minimum of 45 seconds to complete once) to each object so that the combined total of seconds adds up | |
to exactly 600? In other words, how do I split 600 into 8 random numbers where each random number is >= 45, and | |
all combined numbers add to 600? |
Work in progress - pay no attention
var tasks = Array(8).fill(0).map(function(v, i) {
return { name: 'task_' + i, runtime: 45 };
});
var budget = 600;
var remainder = budget - Math.ceil(budget / 45) - (tasks.length * 45);
console.log(remainder);
function getRandomIntInclusive(min, max) {
min = Math.ceil(Math.random() * (max - min + 1)) + 1; //The maximum is inclusive and the minimum is inclusive
return min;
}
tasks.forEach(task => {
var time = getRandomIntInclusive(task.runtime, remainder);
console.log(time, remainder);
task.runtime += time;
remainder -= time;
if (remainder <= 0) {
remainder = 0;
}
});
console.log(tasks);
var total = tasks.reduce(function(total, task) {
return total + task.runtime;
}, 0);
console.dir(total);
5 Sept 2019, I've updated with a possible solution and postscript here => https://gist.github.com/dfkaye/29e28a2a1005704e59467417432203b3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think start with an array of runtimes.
If we start with "every task runs for 45 seconds" then we have a maximum of 13 run times we can allocate, with 15 seconds leftover.
Q. do the tasks have maximum run times? or max time after which they can be aborted?
You could then either allocated runtimes by task max time (a task needs 120 seconds to complete, e.g.) and allocate enough runtimes to that task before allocating to the next one, etc.