To run script
node index.js
const getRandomIndex = (start,end) => { | |
return Math.trunc(Math.random() * (end-start) + start); | |
} | |
const giftExchange = (arr)=>{ | |
let length = arr.length; | |
if (length <= 2) { | |
throw new Error("Insufficient friends"); | |
} | |
let map = new Map(); | |
while ([...map.entries()].length < length) { | |
let gifter = arr.shift(); | |
let index = getRandomIndex(0,arr.length-1); | |
if ([...map.values()].includes(arr[index]) || map.get(arr[index]) === gifter){ | |
arr.push(gifter); | |
continue; | |
} | |
map.set(gifter,arr[index]); | |
arr.push(gifter); | |
} | |
let output= ""; | |
for (const [gifter,receiver] of map.entries()){ | |
output+= `${gifter} gives a gift to ${receiver}\n`; | |
} | |
return output; | |
} | |
const run = () => { | |
console.log(giftExchange(["Susan","Beth","Abe","Ardi", "Quan"])); | |
console.log(giftExchange(["Susan","Beth","Abe","Ardi", "Quan","Nick","Tom","Hamsa","Helen"])); | |
console.log(giftExchange(["Susan","Beth"])); | |
} | |
run() |