简体   繁体   中英

Invoke a function multiple times with the same argument JavaScript

I'm writing a "Secret Santa" function that takes an array of names and matches them randomly with other names in the same array (and they can't match with themselves).

I've got the initial portion working, but now I need to make it so it runs the function twice, and then make sure no one gets the same person two years in a row. For the life of me, I cannot get the function to run twice and create two separate outputs (except with console.log, but since I need to compare the outputs that won't help me).

Code:

var family = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii']

function secretSanta() {
var yourPick = [];
var receivers = family.slice();
var length = family.length;
for (var i = 0; i < length; i++) {
  var giver = family[i];
  var receiverIndex = Math.floor(Math.random() * receivers.length);
     while (receivers[receiverIndex] === giver) {

       receiverIndex = Math.floor(Math.random() * receivers.length);
     }
     var receiver = receivers.splice(receiverIndex, 1)[0];
    yourPick.push({
      Giver: giver,
      Receiver: receiver
    });
}
return yourPick;
}
secretSanta()

I've tried iteration

for (var i = 1; i < 3; i++) secretSanta(i)

Recursion

(function repeat(number) {
    secretSanta(number);
    if (number < 3) repeat(number + 1);
})(1);

and functor application

[1, 2, 3].forEach(secretSanta);

But I either get undefined, an infinite loop, or "maximum stack size exceeded"

Thanks for everyone's help!

All possible different pairs in random order.

 var family = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii'] var pairs = []; for(let i = 0; i<family.length; i++){ for(let j = i+1; j<family.length; j++){ pairs.push([family[i], family[j]]) } } while(pairs.length){ let pair = Math.floor(Math.random() * pairs.length) let temp = pairs.splice(pair,1); if(Math.floor(Math.random()*2)) temp[0].reverse()//<-- pair order console.log(temp[0].join(" - ")) } 

The while is just to pick the pairs randomly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM