DEV Community

Discussion on: Daily Challenge #17 - Double Trouble

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

JavaScript

const cola = (number, people) => {
  const length = people.length;
  const iteration = Math.floor(Math.log2(((number - 1) / length) + 1));
  const post = 2 ** iteration;

  return people[Math.floor((number - ((post - 1) * length + 1)) / post)]
}
Enter fullscreen mode Exit fullscreen mode

The way it works, the series follows an exponential pattern in which the first iteration has n elements (5 in this case), and from then on each iteration has double the elements than the previous iteration:

Iteration(0) = S, L, P, R, H (5 elements)
Iteration(1) = S, S, L, L, P, P, R, R, H, H (10 elements)
Iteration(2) = S, S, S, S, L, L, L, L, P, P, P, P, R, R, R, R, H, H, H, H (20 elements)
Iteration(3) = S, S, S, S, S, S, S, S, S, L, L, L, L, L, L, L, L, ... (40 elements);
Iteration(4) = S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, S, ... (80 elements)

With that in mind, it is possible to calculate in which iteration we are by doing log2(number / 5), and from there we can get which element within the actual iteration we need to check. After doing some numbers, trying to figure out the pattern, and all that jazz, I think this may work... although I haven't fully tested it.

Live demo on Codepen.

Collapse
 
kvharish profile image
K.V.Harish

I like what you are doing here. Kudos :)

Collapse
 
oscherler profile image
Olivier “Ölbaum” Scherler

It seems to work. I tested it (ported to Erlang) with N up to 22 on a queue of 3 people.