How to set a button to select a random integer from an array once?
Well I have an array and a button to select a random integer from the array, how do I make it so that it selects every integer once til all are selected, then it starts over again?
For example, an array has these:
A
B
1
2
Q
F
So you press the button a number of times, and you get:
Q
B
1
F
A
2
Instead of:
1
Q
A
1
B
A
Last edited by Toxhicide; 12-19-2010 at 04:11 AM..
<html>
<head>
<script type="text/javascript">
var values = [ "A","B","1","2","Q","F" ];
var choice = 99999;
var lastValue = "";
function next( )
{
if ( ++choice >= values.length )
{
values.sort( function() { return Math.random() - 0.5; } );
choice = 0;
// OPTIONAL CODE: Prevent the same value appearing last in one
// sequence and then first in the next!!!
while ( values[0] == lastValue ) {
values.sort( function() { return Math.random() - 0.5; } );
}
// END OPTIONAL CODE
}
lastValue = values[choice];
// put it some place
document.getElementById("here").innerHTML = lastValue;
// and/or return it
return lastValue;
}
</script>
</head>
<body>
<form><input type="button" value="Next value" onclick="next()"></form>
<br><br>
<h1 id="here"></h1>
</body>
</html>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
How the array is created makes NO DIFFERENCE AT ALL.
Yes it works, but it seems a lot less random. I used the way you had said and it does work, but these are my results from having 52 numbers, four two through nines, sixteen tens, and four elevens. These are my results from pressing it a number of times.
As I understand it you want to shuffle the array so that the same element does not appear twice. That is not the same as chosing a series of random array elements, as of course random numbers can (and very likely will) repeat.
You mention 52. Are you trying to shuffle a pack of playing cards?
Code:
<script type = "text/javascript">
var cardsArray = new Array('Ace ♥','Ace ♣','Ace ♦','Ace ♠', '2 ♥','2 ♣','2 ♦','2 ♠','3 ♥','3 ♣','3 ♦','3 ♠','4 ♥','4 ♣','4 ♦','4 ♠','5 ♥','5 ♣','5 ♦','5 ♠','6 ♥','6 ♣','6 ♦','6 ♠','7 ♥','7 ♣','7 ♦','7 ♠','8 ♥','8 ♣','8 ♦','8 ♠','9 ♥','9 ♣','9 ♦','9 ♠','10 ♥','10 ♣','10 ♦','10 ♠','Jack ♥','Jack ♣','Jack ♦','Jack ♠','Queen ♥','Queen ♣','Queen ♦','Queen ♠','King ♥','King ♣','King ♦','King ♠');
function randOrd(){return (Math.round(Math.random())-0.5); }
cardsArray.sort(randOrd);
var count = 0;
function getCard() {
document.getElementById("theCard").innerHTML = cardsArray[count];
count++;
if (count >51) {
count = 0;
cardsArray.sort(randOrd); // shuffle the cards again
}
}
</script>
</head>
<body>
<input type = "button" value = "Get Next Card" onclick = "getCard()">
<br><br>
<span id = "theCard"></span><br><br>
In any case you should be able to adapt the above code to meet you needs (assuming that the array values are strings, not numbers which require a different sort algorithm).
Last edited by Philip M; 12-18-2010 at 08:54 AM..
Reason: typo
Here's something I put together for you, it does use a function called in_array which was taken from the phpjs.org website but the keygen function was built by myself, I did also use Philip M's math function for selecting a random char each time.
Here's the working code.
Note: You may get the same char twice such as 'zZ' but this is a result of having both upper and lower case in the keygen array.
Code:
<!DOCTYPE html>
<html>
<head>
<title>KeyGen</title>
<script type="text/javascript">
(function($){
$.in_array = function(needle,haystack,argStrict) {
// Checks if the given value exists in the array
// version: 1009.2513
// discuss at: http://phpjs.org/functions/in_array
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: vlado houba
// + input by: Billy
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// * example 1: in_array('van',['Kevin','van','Zonneveld']); returns 1: true
// * example 2: in_array('vlado',{0:'Kevin',vlado:'van',1:'Zonneveld'}); returns 2: false
// * example 3: in_array(1,['1','2','3']); returns 3: true
// * example 3: in_array(1,['1','2','3'], false); returns 3: true
// * example 4: in_array(1,['1','2','3'], true); returns 4: false
var key = '', strict = !!argStrict;
if(strict) {
for(key in haystack) {
if(haystack[key]===needle) {return true;}
}
} else {
for(key in haystack) {
if(haystack[key]==needle) {return true;}
}
}
return false;
};
/**
* @Function: KeyGen :: PUBLIC
* Generates a unique key with different
* chars in each key and no chars in the
* key are ever the same.
*
* Built by CMBSystems (Chris Bearcroft)
*/
var keygen = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
hidden = [],
limit = 26,
sGen = function(){return Math.random()-0.5;};
$.KeyGen = function() {
var i,k=[];
keygen.sort(sGen);
for(i=0;i<limit;i++) {
if(!$.in_array(keygen[i],hidden)) {
k[i] = keygen[i];
hidden.push(keygen[i]);
keygen.sort(sGen);
}
}
hidden = [];
document.getElementById('keygen').innerHTML = k.join('');
};
})(window);
</script>
</head>
<body>
<input type="button" value="KeyGen" onclick="return KeyGen();" />
<div id="keygen"></div>
</body>
</html>
__________________
Official BinPress hand picked coder.
For anyone worried about SQL injection go have a look at my small yet powerful script here.
Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
I am 1 of 65,608 people to get a Pebble Watch :P
After re-reading your question again I understood what you wanted to do.
Basicly you want to have an array of items such as ['A','B',1,2,'Q','F'] and have each item display only once through the array cycle and once it has displayed all items in the array to then allow the items go through the loop again only displaying each item once, and you want it to have an endless loop so you get a different array item each time you click the button.
I re-wrote the code in my past post which now does what you want.
Code:
<!DOCTYPE html>
<html>
<head>
<title>KeyGen</title>
<script type="text/javascript">
(function($){
$.in_array = function(needle,haystack,argStrict) {
// Checks if the given value exists in the array
// version: 1009.2513
// discuss at: http://phpjs.org/functions/in_array
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: vlado houba
// + input by: Billy
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// * example 1: in_array('van',['Kevin','van','Zonneveld']); returns 1: true
// * example 2: in_array('vlado',{0:'Kevin',vlado:'van',1:'Zonneveld'}); returns 2: false
// * example 3: in_array(1,['1','2','3']); returns 3: true
// * example 3: in_array(1,['1','2','3'], false); returns 3: true
// * example 4: in_array(1,['1','2','3'], true); returns 4: false
var key = '', strict = !!argStrict;
if(strict) {
for(key in haystack) {
if(haystack[key]===needle) {return true;}
}
} else {
for(key in haystack) {
if(haystack[key]==needle) {return true;}
}
}
return false;
};
/**
* @Function: KeyGen :: PUBLIC
* Generates a unique key with different
* chars in each key and no chars in the
* key are ever the same.
*
* Built by CMBSystems (Chris Bearcroft)
*/
var keygen = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
gend = [],
sGen = function(){return Math.random()-0.5;};
$.KeyGen = function() {
keygen.sort(sGen);
if(!$.in_array(keygen[0],gend)) {
gend.push(keygen[0]);
document.getElementById('keygen').innerHTML = keygen[0];
if((keygen.length-gend.length)===0) {gend = [];} // Empty gend array
} else {
$.KeyGen();
}
};
})(window);
</script>
</head>
<body>
<input type="button" value="KeyGen" onclick="return KeyGen();" />
<div id="keygen"></div>
</body>
</html>
__________________
Official BinPress hand picked coder.
For anyone worried about SQL injection go have a look at my small yet powerful script here.
Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
I am 1 of 65,608 people to get a Pebble Watch :P
As I understand it you want to shuffle the array so that the same element does not appear twice. That is not the same as chosing a series of random array elements, as of course random numbers can (and very likely will) repeat.
You mention 52. Are you trying to shuffle a pack of playing cards?
Code:
<script type = "text/javascript">
var cardsArray = new Array('Ace ♥','Ace ♣','Ace ♦','Ace ♠', '2 ♥','2 ♣','2 ♦','2 ♠','3 ♥','3 ♣','3 ♦','3 ♠','4 ♥','4 ♣','4 ♦','4 ♠','5 ♥','5 ♣','5 ♦','5 ♠','6 ♥','6 ♣','6 ♦','6 ♠','7 ♥','7 ♣','7 ♦','7 ♠','8 ♥','8 ♣','8 ♦','8 ♠','9 ♥','9 ♣','9 ♦','9 ♠','10 ♥','10 ♣','10 ♦','10 ♠','Jack ♥','Jack ♣','Jack ♦','Jack ♠','Queen ♥','Queen ♣','Queen ♦','Queen ♠','King ♥','King ♣','King ♦','King ♠');
function randOrd(){return (Math.round(Math.random())-0.5); }
cardsArray.sort(randOrd);
var count = 0;
function getCard() {
document.getElementById("theCard").innerHTML = cardsArray[count];
count++;
if (count >51) {
count = 0;
cardsArray.sort(randOrd); // shuffle the cards again
}
}
</script>
</head>
<body>
<input type = "button" value = "Get Next Card" onclick = "getCard()">
<br><br>
<span id = "theCard"></span><br><br>
In any case you should be able to adapt the above code to meet you needs (assuming that the array values are strings, not numbers which require a different sort algorithm).
My array has numbers and letters, but this seemed to work nonetheless. I had gotten these values, much better than the last code (and they dont repeat ):
After re-reading your question again I understood what you wanted to do.
Basicly you want to have an array of items such as ['A','B',1,2,'Q','F'] and have each item display only once through the array cycle and once it has displayed all items in the array to then allow the items go through the loop again only displaying each item once, and you want it to have an endless loop so you get a different array item each time you click the button.
I re-wrote the code in my past post which now does what you want.
Code:
<!DOCTYPE html>
<html>
<head>
<title>KeyGen</title>
<script type="text/javascript">
(function($){
$.in_array = function(needle,haystack,argStrict) {
// Checks if the given value exists in the array
// version: 1009.2513
// discuss at: http://phpjs.org/functions/in_array
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: vlado houba
// + input by: Billy
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// * example 1: in_array('van',['Kevin','van','Zonneveld']); returns 1: true
// * example 2: in_array('vlado',{0:'Kevin',vlado:'van',1:'Zonneveld'}); returns 2: false
// * example 3: in_array(1,['1','2','3']); returns 3: true
// * example 3: in_array(1,['1','2','3'], false); returns 3: true
// * example 4: in_array(1,['1','2','3'], true); returns 4: false
var key = '', strict = !!argStrict;
if(strict) {
for(key in haystack) {
if(haystack[key]===needle) {return true;}
}
} else {
for(key in haystack) {
if(haystack[key]==needle) {return true;}
}
}
return false;
};
/**
* @Function: KeyGen :: PUBLIC
* Generates a unique key with different
* chars in each key and no chars in the
* key are ever the same.
*
* Built by CMBSystems (Chris Bearcroft)
*/
var keygen = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
gend = [],
sGen = function(){return Math.random()-0.5;};
$.KeyGen = function() {
keygen.sort(sGen);
if(!$.in_array(keygen[0],gend)) {
gend.push(keygen[0]);
document.getElementById('keygen').innerHTML = keygen[0];
if((keygen.length-gend.length)===0) {gend = [];} // Empty gend array
} else {
$.KeyGen();
}
};
})(window);
</script>
</head>
<body>
<input type="button" value="KeyGen" onclick="return KeyGen();" />
<div id="keygen"></div>
</body>
</html>
This did seem to work for what I am trying to do, but I couldnt get a part of the array I wanted, it would only come out as either 2,"Text",3, or 2 if I had messed with the values enough. I couldnt make Card[0][1] come up as Text.
Math.random returns a number between 0 and 1.
Math.round then rounds that number so that it is 0 if the number was under 0.5 and 1 if it was over 0.5.
0.5 is then subtracted giving either -0.5 or 0.5 depending on whether it was rounded to 0 or 1.
Whether the final result is positive or negative determines whether two entries being compared are swapped or left alone.
Math.random returns a number between 0 and 1.
Math.round then rounds that number so that it is 0 if the number was under 0.5 and 1 if it was over 0.5.
0.5 is then subtracted giving either -0.5 or 0.5 depending on whether it was rounded to 0 or 1.
Whether the final result is positive or negative determines whether two entries being compared are swapped or left alone.