[removed] randomly pair items from array without repeats

前端 未结 5 2046
执笔经年
执笔经年 2021-01-05 09:03

I am trying to make a very basic \"secret santa\" generator as one of my first Javascript projects. I have searched for hours for a solution to this problem but so far noth

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 09:34

    I would suggest a different approach. Shuffle, split, and zip, no mutation:

    var splitAt = function(i, xs) {
      var a = xs.slice(0, i);
      var b = xs.slice(i, xs.length);
      return [a, b];
    };
    
    var shuffle = function(xs) {
      return xs.slice(0).sort(function() {
        return .5 - Math.random();
      });
    };
    
    var zip = function(xs) {
      return xs[0].map(function(_,i) {
        return xs.map(function(x) {
          return x[i];
        });
      });
    }
    
    // Obviously assumes even array
    var result = zip(splitAt(names.length/2, shuffle(names)));
    //^
    // [
    //   [ 'Nick', 'Kimmy' ],
    //   [ 'Sean', 'Johnny' ],
    //   [ 'Kyle', 'Brian' ],
    //   [ 'Cotter', 'Pat' ],
    //   [ 'Emily', 'Jeremy' ]
    // ]
    

提交回复
热议问题