user2328058
user2328058

Reputation: 23

JavaScript - Output characters randomly

Not sure how to go about this but I need to output a set of characters x, y and z. The output is 3 characters long and consists of x,y and z. However the characters are as likely as each other. Basically output characters (from a set, in this case x,y and z) randomly. Example outputs - xyy, zzz, yyz etc. I'm guessing I need a function?

Upvotes: 1

Views: 117

Answers (3)

plalx
plalx

Reputation: 43718

A different approach:

DEMO: http://jsfiddle.net/VNh7n/1/

function randomXYZ() {
    return 'xxx'.replace(/x/g, function () {
        return String.fromCharCode(Math.floor(Math.random() * 3) + 120);
    });
}

console.log(randomXYZ());

Upvotes: 1

RobG
RobG

Reputation: 147413

For random combinations where each character only appears once:

function shuffleChars(s) {
  s = s.split('');
  var i = s.length;
  var result = [];
  while (i) {
    result.push(s.splice(Math.floor(Math.random() * (i--)),1));
  }
  return result;
}

For random combinations where a character may appear any number of times up to the length of the string:

function randomChars(s) {
  s = s.split('');
  for (var i=0, iLen=s.length, result=[]; i<iLen; i++) {
    result[i] = s[Math.random() * iLen | 0];
  }
  return result;
}

randomChars('xyz'); 

Both of the above can take strings of any length.

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

You can do something like this:

var chars = ['x','y','z'];
function show_chars(arr){
    var l = arr.length;
    return arr[Math.floor(Math.random()*l)] 
       + arr[Math.floor(Math.random()*l)] 
       + arr[Math.floor(Math.random()*l)]
}
console.log(show_chars(chars));

Upvotes: 1

Related Questions