質問

Let's consider I have the following characters:

H, M, L

I would like to create sorted array(s) like the following:

var array1 = [ "H", "M", "L", "L", "M", "H" ];

What I don't want is for the first three and last three characters containing more than one unique character when I shuffle() the array.

e.g.

var wrong = [ "H", "M", "M", "H", "M", "L" ]; // note the two M's in the first three values

If I use shuffle() like the following:

var array2 = array1.shuffle(); then I run the risk of duplicate characters.

I would like some help in determining the easiest way to ensure there are no duplicated characters in the 1st and 2nd three values in the array?

EDIT: Changed random to sorted.

役に立ちましたか?

解決 2

I ended up going with something like this thanks to @Xotic750's answer.

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

var array = [ "H", "M", "L" ];
var b = array.slice().shuffle().concat(array.slice().shuffle());

JSFiddle output.

他のヒント

Create your shuffle, either on the prototype or as a stand-alone

function shuffle(obj) {
  var i = obj.length;
  var rnd, tmp;

  while (i) {
    rnd = Math.floor(Math.random() * i);
    i -= 1;
    tmp = obj[i];
    obj[i] = obj[rnd];
    obj[rnd] = tmp;
  }

  return obj;
}


var a = ['H', 'M', 'L'],
  b = shuffle(a.slice()).concat(shuffle(a.slice()));

console.log(b);

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top