Skip to content

Instantly share code, notes, and snippets.

@tevko
Created December 18, 2018 15:13
Show Gist options
  • Save tevko/20f8fc446d219f4714517aab19c5dd71 to your computer and use it in GitHub Desktop.
Save tevko/20f8fc446d219f4714517aab19c5dd71 to your computer and use it in GitHub Desktop.
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?
@dfkaye
Copy link

dfkaye commented Dec 19, 2018

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);

@dfkaye
Copy link

dfkaye commented Sep 5, 2019

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