1

How can I create a generator where when a button is pressed it selects a random word that I've added to a list.

For example, "Apple", "Banana" and "Pear" are on my list and I want the end user to press a button and the code will fetch one of the fruits but completely randomly, how can I do this?

Regards, John

CCC
  • 49
  • 4

4 Answers4

5

First, you mention a list; this directly translates to an array. Second, you have a finite number of options, presented in the array, and you want to pick one at random. This translates to picking an index (integer) at random. Since arrays start at 0 and you cannot choose an item passed the last index, you will then need to choose a random range between 0 and the length of the array.

If you simply want to get a random item from a list from pressing a button, you'll most certainly want to isolate this to the front-end, i.e. javascript:

var randomWords = [
    'Apple',
    'Banana',
    'Pear'
];

function getRandomWordFromList(list) {
    var index = getRandomInt(0,list.length);
    return randomWords[index];
}

function getRandomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

document.getElementById('myButton').onclick = function() { // for example's sake...
    document.getElementById('theOutput').innerHTML = getRandomWordFromList(randomWords);
};

(getRandomInt from Generating random whole numbers in JavaScript in a specific range?)

Also, if your array is fragmented (i.e. some indices are missing), you can use (safer, albeit more convoluted):

function arrayKeys(array) {
    var i,keys = [];
    for ( i in array ) {
        if ( isInt(i) && array.hasOwnProperty(i) ) {
            keys.push(i);
        }
    }
    return keys;
}

function isInt(value) { 
    return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); 
}

function getRandomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomWordFromList(list) {
    var keys = arrayKeys(list); // be sure to only get indices that exist
    var key = getRandomInt(0,keys.length-1);
    return list[keys[key]];
}

var randomWords = [
    'Apple',
    'Banana',
    'Pear'
];

delete randomWords[1]; // remove 'Banana'

var theWord = getRandomWordFromList(randomWords);

If there is something server-side that influences the randomized list, you can populate the randomWords array via PHP as follows:

<?php
$randomWords = array(
    'Apple',
    'Banana',
    'Pear'
);
?>
<script type="text/javascript">
var randomWords = [<?php echo "'".implode("','",$randomWords)."'"; ?>];
// don't forget your getRandomWord functions
</script>

Bonus: If the randomization must happen entirely server-side, i.e. php, here is a translation:

<?php
$randomWords = array(
    'Apple',
    'Banana',
    'Pear'
);

echo $randomWords[array_rand($randomWords)]; // output somewhere
?>
Community
  • 1
  • 1
zamnuts
  • 9,492
  • 3
  • 39
  • 46
1

A simple javascript closure to demonstrate.

var generateRandom = (function () {
    var fruit;
    return function () {
        if (fruit === undefined) {
            fruit = ["Apple", "Banana", "Pear"];
        }
        return fruit[Math.floor(Math.random() * fruit.length)];
    }
}());

Here Math.random gives a number between 0 and 1. so I will be multiplying it with the array length to get a number between 0 and fruit.length. this would be the index of the item that we are going to pick.

madrag
  • 1,685
  • 1
  • 9
  • 4
0

Using Javascript:

var fruit;
var rand = Math.random();
if (rand <= 0.33) {
  fruit = 'Apple';
} else if (rand > 0.34 && rand <= 0.66) {
  fruit = 'Banana';
} else if (rand > 0.67) {
  fruit = 'Pear';
}

Math.random() will return a number between 0 and 1.

Deryck
  • 7,608
  • 2
  • 24
  • 43
0

Here's just a quick example of how to might do this. Actions (clicking in this case) are taken care of by JavaScript, so I highly recommend taking care of all of it there. The idea is that you don't need to have separate html or especially php worry about this when you could package it up in a JavaScript object. This code is far from perfect, but I think it's a good starting point for you. Notice that all you need to do to make this run is have this script included and simply type (in js) wordRandomizer.run(myElem); when myElem is a reference to an element that is in the dom (I just used the body in this example).

Demo here.

var wordRandomizer = { //the name of your "app"
  run : function(targetElem) { //this is the function you will call to make it all happen
    var markup = this.createMarkup();
    targetElem.appendChild(markup);
  },
  createMarkup : function() {
    var that = this;
    var frag = document.createDocumentFragment();

    this.elem = document.createElement('span');

    var button = document.createElement('button');
    button.innerText = 'Change Item';
    button.addEventListener('click', function() {
      that.changeItem();
    });

    frag.appendChild(this.elem);
    frag.appendChild(button);

    return frag;
  },
  changeItem : function() {
    var rand = this.getRandInt(1, this.items.length) - 1; // -1 because arrays start at 0
    this.elem.innerText = this.items[rand];
  },
  getRandInt : function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  items : [
    'itemA',
    'itemB',
    'itemC',
    'itemD'
  ]
};

wordRandomizer.run(document.body); 
//here, you just pass in the element where your "app" will attach its output. 
//If you want to get fancier, you could make more things optional, add more functionality, etc and pass in those options here.

Oh, and you should add some logic to make sure the item selected will not be the same item as before. There's several ways to do that easily, but I'll leave the fun to you :)

m59
  • 43,214
  • 14
  • 119
  • 136
  • Thanks for this! Appreciate it alot. Using it now, however I don't know how to put the button on a separate line from the randomly generated item and I also don't even know how to center the whole script as every time I try the button disappears so obviously I am doing it wrong. – CCC Oct 29 '13 at 01:25
  • You can change what the elements are in `document.createElement('elementTypeHere')` and use CSS to style them however you want. @CCC – m59 Oct 29 '13 at 03:43