A team app runs a gift exchange: everyone gives one gift and gets one, nobody draws themselves, and all gifts form one big circle. It uses a variant of Fisher-Yates called Sattolo's algorithm.
Start with order = [0, 1, ..., n - 1]. For i from n - 1 down to 1, take the next number r from randoms (in order), set j = Math.floor(r * i) (so j is always less than i), and swap order[i] and order[j]. Then person names[i] gives a gift to names[order[i]].
Write giftExchange(names, randoms) that returns an array where item i is the name of the person names[i] gives to.
Input: names = ["Ana","Ben","Cy"], randoms = [0.5,0.9] Output: ["Cy","Ana","Ben"]
i = 2: j = 1, so order is [0, 2, 1]. i = 1: j = 0, so order is [2, 0, 1]. Ana gives to Cy, Ben to Ana, Cy to Ben.
Input: names = ["A","B"], randoms = [0.3] Output: ["B","A"]
With two people, they must swap gifts.
2 <= names.length <= 1000randoms.length === names.length - 10 <= randoms[i] < 1Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #88 Secret Gift Exchange. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.