Shuffle and slice an array into fixed-size chunks
Anonymous
I had to write some code on the whiteboard. I could use any language, so I chose JS . First, I explained that there are different algorithms for shuffling arrays and assumed that Fisher–Yates algorithm is appropriate for that question. Then wrote something like the this: const shuffle = (arr) => new Array(arr.length) .fill(0) .map((_, i) => Math.floor((i + 1) * Math.random())) .reduce((acc, swapIndex, arrIndex) => { // they stopped me around here and said I can assume that this function already exists // the following has side-effects, but one can map acc to another array in which the elements at arrIndex and swapIndex are swapped. acc[arrIndex] = acc[swapIndex]; acc[swapIndex] = arr[arrIndex]; return acc; }, [...arr]); They stopped me in the middle and said I can assume that the shuffle function already exists. Then I continued: partition = (arr, k) => shuffle(arr).reduce((acc, element) => { if (acc.length === 0 || acc[acc.length - 1].length === k) { return [...acc, [element]]; } else { // they kinda stopped me here const last = acc[acc.length - 1]; return [...acc.slice(0, acc.length - 1), [...last, element]]; } }, []); It seemed that they didn't understand how the code works and found the functional style programming I did there "a bit more complex than necessary". They didn't ask me/give me a chance to rewrite that in an imperative style. Then an interviewer asked me to solve the same problem for an array that doesn't fit in memory. I explained briefly how that can be done and we moved on to the next question.
Check out your Company Bowl for anonymous work chats.