user2873801
user2873801

Reputation: 25

Group Randomly Printed Strings into Groups of Two

I'm looking to group randomly printed strings into groups of two.

Here is my JavaScript code used to randomize the strings:

Array.prototype.shuffle= function(times){
    var i,j,t,l=this.length;
    while(times--){
        with(Math){
            i=floor(random()*l);j=floor(random()*l);
        }
        t=this[i];this[i]=this[j];this[j]=t;
    }
    return this;
}

var players=["Ben","Caleb","Alex","Ryder","Brad","Garret","Justin","John","Kevin"]

document.write(players.shuffle(200).join("<BR>") )

Obviously, at this time the print order is

NAME 
NAME
NAME
NAME
NAME
NAME
NAME
NAME
NAME

However I'd like it to be

NAME NAME
NAME NAME
NAME NAME
NAME NAME
NAME

How would I go about doing this?

Upvotes: 0

Views: 64

Answers (3)

RobG
RobG

Reputation: 147483

Just a comment:

with is greatly disliked and will be removed in a future version of ECMAScript. It's use here is entirely gratuitous, consider the equivalent:

    i = Math.random() * l | 0;
    j = Math.random() * l | 0;

In regard to printing out the members in twos, consider:

// Only increment by 1 in the condition
for(var i=0, iLen=players.length; i<iLen; i++) {

    // Second increment is in here
    console.log(players[i] + " " + (++i in players? players[i] : ''));
}

So if there are 3 items (i.e. items at index 0, 1 and 2) when it tests for 3 in players it will return false and nothing is printed.

You could also do:

    console.log(players[i] + " " + (++i < iLen? players[i] : ''));

Upvotes: 0

Kirk
Kirk

Reputation: 513

# first get your shuffled players
shuffled_players = players.shuffle(200)

# loop through them
for(var i=0; i<shuffled_players.length; i++){
  document.write(shuffled_players[i]);
  # put either a space or break
  document.write(i%2 == 0 ? " " : "<BR>");
}

Upvotes: 0

mdolbin
mdolbin

Reputation: 936

for(var i=1; i<players.length+1; i+=2){
    console.log(players[i-1]+" "+((players[i]!=undefined)?players[i]:""));
}

or

for(var i=0; i<players.length; i+=2){
    console.log(players[i]+" "+((players[i+1]!=undefined)?players[i]:""));
}

You can use it this way:

Array.prototype.shuffle= function(times){
    var i,j,t,l=this.length;
    while(times--){
        with(Math){
            i=floor(random()*l);j=floor(random()*l);
        }
        t=this[i];this[i]=this[j];this[j]=t;
    }
    return this;
}

var players=["Ben","Caleb","Alex","Ryder","Brad","Garret","Justin","John","Kevin"]
players.shuffle(200);

for(var i=0; i<players.length; i+=2){
    document.write(players[i]+" "+((players[i+1]!=undefined)?players[i+1]:"")+"<br>");
}

Upvotes: 1

Related Questions