DEV Community

Discussion on: Shuffle the Array (Javascript)

Collapse
 
pentacular profile image
pentacular

When I see this kind of problem, my first thought is to see if it can be decomposed into a couple of simpler problems.

Here I think we can turn it into 'partition' and 'zip', and I think this is the insight that I'd be looking for if I were asking this as an interview question.

const partition = (array) => [array.slice(0, array.length / 2), array.slice(array.length / 2)];

const zip = (a, b) => {
  const zipped = [];
  const limit = Math.max(a.length, b.length);
  for (let nth = 0; nth < limit; nth++) {
    if (a[nth] !== undefined) {
      zipped.push(a[nth]);
    }
    if (b[nth] !== undefined) {
      zipped.push(b[nth]);
    }
  }
  return zipped;
}

const shuffle = (array) => zip(...partition(array));
Enter fullscreen mode Exit fullscreen mode

I'd then have a conversation about efficiency, and might come up with a composed version closer to what you've shown above, if the interviewer were interested in following that path.

Anyhow, just thought I'd offer another perspective -- good luck. :)

Collapse
 
javila35 profile image
Joe Avila

Thanks. I hadn't heard of a zip before, but it seems pretty common in CS.

Collapse
 
pentacular profile image
pentacular

You're welcome.