0

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.

3
  • 1
    If you have such conditions, then it is not "random". Maybe you want to sort instead of shuffle? Commented Feb 20, 2014 at 0:12
  • 2
    var a = ['H', 'M', 'L']; var b = a.slice().shuffle().concat(a.slice().shuffle()); perhaps? Commented Feb 20, 2014 at 0:14
  • @Xotic750 that seemed to do the trick, thanks. Feel free to add it as an answer and I'll accept it. Commented Feb 20, 2014 at 0:21

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.