PDA

View Full Version : Resolved How to set a button to select a random integer from an array once?

Toxhicide
12-18-2010, 12:31 AM
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

1
Q
A
1
B
A

Old Pedant
12-18-2010, 01:27 AM
<html>
<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>
<body>
<form><input type="button" value="Next value" onclick="next()"></form>
<br><br>
<h1 id="here"></h1>
</body>
</html>

Toxhicide
12-18-2010, 03:50 AM
How would you make that work in this type of array?

CD = []

CD[CD.length] = [,"",]

As of now I use to get random numbers,, which works great, but they repeat:

for (c=0;c<CD.length;c++){
randD = CD[Math.floor(Math.random()*CD.length)]
document.getElementById('c1').value = randD

Old Pedant
12-18-2010, 05:09 AM
How the array is created makes NO DIFFERENCE AT ALL.

Toxhicide
12-18-2010, 05:20 AM
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.

10
2
4
10
3
4
11
4
10
4
2
11
10
3
10
11
10
3
5
11
10
10
2
10
3
10
5
2
10
10
5
5
10
10

I seem to hit a lot of the same numbers, and every time I test it I get the same results, not as random as I hope.

Philip M
12-18-2010, 08:49 AM
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?

<script type = "text/javascript">

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>

<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).

DJCMBear
12-18-2010, 01:04 PM
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.

<!DOCTYPE html>
<html>
<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 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>
<body>
<input type="button" value="KeyGen" onclick="return KeyGen();" />
<div id="keygen"></div>
</body>
</html>

Sciliano
12-18-2010, 01:50 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<title>Deal 10 Cards - No Duplicates</title>
<script type="text/javascript">

function deal(nDisplay){

var randomArray = [];
var card = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"];
var cards = "";
for (i=1; i<=52; i++)
{
randomArray[i-1] = i;
}
for (i=0; i<randomArray.length; i++)
{
var tmp1 = parseInt(Math.random()*randomArray.length);
var tmp2 = parseInt(Math.random()*randomArray.length);
var tmp3 = randomArray[tmp1];
randomArray[tmp1] = randomArray[tmp2];
randomArray[tmp2] = tmp3;
}
for (i=0; i<10; i++)
{
if (randomArray[i] < 14)
{
cards += "<span class='red'>" + card[randomArray[i]-1] + "&hearts;" + "<\/span>";
}
else if (randomArray[i] > 13 && randomArray[i] < 27)
{
cards += "<span class='black'>" + card[randomArray[i]-14] + "&clubs;" + "<\/span>";
}
else if (randomArray[i] > 26 && randomArray[i] < 40)
{
cards += "<span class='red'>" + card[randomArray[i]-27] + "&diams;" + "<\/span>";
}
else if (randomArray[i] > 39)
{
cards += "<span class='black'>" + card[randomArray[i]-40] + "&spades;" + "<\/span>";
}
}
nDisplay.innerHTML = cards;
}

function init(){

var nDiv = document.getElementsByTagName('div');
for (i=0; i<nDiv.length; i++)
{
if (nDiv[i].className == "dealBtn")
{
var nDealBtn = nDiv[i].firstChild;
}
if (nDiv[i].className == "dealtCards")
{
var nDisplay = nDiv[i];
}
}
nDealBtn.onclick = function(){deal(nDisplay)}
}

</script>
<style type="text/css">

body {margin-top: 65px; background-color: #f0fff0;}
.dealtCards {width: 450px; height: 25px; margin: auto; font-size: 16pt;
background-color: #f6eabc; padding: 5px; border: 1px solid black; text-align: center;}
.dealBtn input {background-color: #ffffff; border: 1px solid #000000; font-family: arial; font-size: 10pt;
font-weight: bold; cursor: pointer; display: block; margin-left: auto; margin-right: auto;
margin-top: 35px; margin-bottom: 0px;}
.red {font-family: arial; color: #ff0000; margin-left: 8px; margin-right: 8px;}
.black {font-family: arial; color: #000000; margin-left: 8px; margin-right: 8px;}

</style>
<body>

<div class="dealtCards"></div>

<div class="dealBtn"><input type="button" value="Deal 10 Cards"></div>

</body>
</html>

DJCMBear
12-18-2010, 02:42 PM
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.

<!DOCTYPE html>
<html>
<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 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>
<body>
<input type="button" value="KeyGen" onclick="return KeyGen();" />
<div id="keygen"></div>
</body>
</html>

Philip M
12-18-2010, 05:51 PM
No, he wants to deal playing cards.

Toxhicide
12-18-2010, 06:31 PM
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?

<script type = "text/javascript">

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>

<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 :)):

5
10
3
4
4
8
5
3
5
6
7
2
6
11
10
9
10
2
8
9
10
10
9
8
6

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.

<!DOCTYPE html>
<html>
<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 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>
<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.

No, he wants to deal playing cards.

Yes, that is what Im trying to do, and your card shuffler seemed to work. Thank you. Would you mind explaining the - 0.5?

Philip M
12-18-2010, 07:34 PM
. Would you mind explaining the - 0.5?

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.

Toxhicide
12-18-2010, 07:53 PM
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.

Oh I see. Thanks again.