DEV Community

Discussion on: Daily Challenge #25 - Double Cola

Collapse
 
ynndvn profile image
La blatte

Had to do a few tweaks to allow large numbers to be used as index:

const whoIsNext = (queue, index) => {
  queue = queue.map(e=>[e,1]);
  let qi = 0, j = 0;
  while (j < index) {
    j += queue[qi][1]*=2;
    qi = (qi+1) % queue.length;
  }
  return queue[(queue.length+qi-1)%queue.length][0];
}

Instead of pushing values in a large array, everything is stored in a 2-dimensional one:

whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951)
"Leonard"

// "queue" will store the following value in the end:
[["Sheldon", 1073741824],
 ["Leonard", 1073741824],
 ["Penny", 536870912],
 ["Rajesh", 536870912],
 ["Howard", 536870912]]