Get Certified on your expert knowledge

Brainbench grant you full access to assessments and certifications covering over 600 skills in demand for today's marketplace.
Visit the site and get certified. Click Here to take some FREE tests.

Monday, June 11, 2012

To produce random unique numbers by javascript

HTML Structure:
<label>Enter the Max limit random valuelabel>
<input type="text" value="" id="txtmaxvalue"/><br/>
<input type="button" value="Keep clicking me to get random values" onclick="randomise()"/>
<div id="showme">div>

Javascript code:
var rndno;
var arraylist = [];
var showme = document.getElementById("showme");
var hasvalue = false;

function randomise() {
    var maxvalue = document.getElementById("txtmaxvalue").value;
    findnumber(maxvalue);
    showme.innerHTML = "";
    for (var i = 0; i < arraylist.length; i++) {
        showme.innerHTML = showme.innerHTML + arraylist[i] + ", ";
    }
}

function findnumber(maxvalue) {
    rndno = Math.random();
    rndno = Math.floor(rndno * maxvalue);
    for (var k = 0; k < arraylist.length; k++) {
        if (arraylist[k] == rndno) {
            hasvalue = true;
            break;
        }
        else {
            hasvalue = false;
        }
    }
    if (!hasvalue) arraylist.push(rndno);
}

You can see the demo here

No comments:

Post a Comment