Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New Coder
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    4
    Thanked 0 Times in 0 Posts

    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 05:11 AM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,158
    Thanks
    80
    Thanked 4,559 Times in 4,523 Posts
    Code:
    <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.

  • #3
    New Coder
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    4
    Thanked 0 Times in 0 Posts
    How would you make that work in this type of array?

    Code:
    CD = []
    
    CD[CD.length] = [,"",]
    As of now I use to get random numbers,, which works great, but they repeat:

    Code:
    for (c=0;c<CD.length;c++){
    randD = CD[Math.floor(Math.random()*CD.length)]
    document.getElementById('c1').value = randD
    Last edited by Toxhicide; 12-18-2010 at 04:57 AM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,158
    Thanks
    80
    Thanked 4,559 Times in 4,523 Posts
    How the array is created makes NO DIFFERENCE AT ALL.
    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.

  • #5
    New Coder
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    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.

    Code:
    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.

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,247
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    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 &hearts;','Ace &clubs;','Ace &diams;','Ace &spades;', '2 &hearts;','2 &clubs;','2 &diams;','2 &spades;','3 &hearts;','3 &clubs;','3 &diams;','3 &spades;','4 &hearts;','4 &clubs;','4 &diams;','4 &spades;','5 &hearts;','5 &clubs;','5 &diams;','5 &spades;','6 &hearts;','6 &clubs;','6 &diams;','6 &spades;','7 &hearts;','7 &clubs;','7 &diams;','7 &spades;','8 &hearts;','8 &clubs;','8 &diams;','8 &spades;','9 &hearts;','9 &clubs;','9 &diams;','9 &spades;','10 &hearts;','10 &clubs;','10 &diams;','10 &spades;','Jack &hearts;','Jack &clubs;','Jack &diams;','Jack &spades;','Queen &hearts;','Queen &clubs;','Queen &diams;','Queen &spades;','King &hearts;','King &clubs;','King &diams;','King &spades;'); 
    
    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 09:54 AM. Reason: typo

  • Users who have thanked Philip M for this post:

    Toxhicide (12-18-2010)

  • #7
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    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>
    Last edited by DJCMBear; 12-18-2010 at 02:08 PM.
    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

  • #8
    Regular Coder
    Join Date
    Nov 2009
    Posts
    247
    Thanks
    4
    Thanked 22 Times in 22 Posts
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <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)}
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </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>
    </head>
    <body>
    
    	<div class="dealtCards"></div>
    	
    	<div class="dealBtn"><input type="button" value="Deal 10 Cards"></div>
    
    </body>
    </html>

  • #9
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    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

  • Users who have thanked DJCMBear for this post:

    Toxhicide (12-18-2010)

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,247
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    No, he wants to deal playing cards.

    http://www.codingforums.com/showthread.php?t=212539

  • #11
    New Coder
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    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 &hearts;','Ace &clubs;','Ace &diams;','Ace &spades;', '2 &hearts;','2 &clubs;','2 &diams;','2 &spades;','3 &hearts;','3 &clubs;','3 &diams;','3 &spades;','4 &hearts;','4 &clubs;','4 &diams;','4 &spades;','5 &hearts;','5 &clubs;','5 &diams;','5 &spades;','6 &hearts;','6 &clubs;','6 &diams;','6 &spades;','7 &hearts;','7 &clubs;','7 &diams;','7 &spades;','8 &hearts;','8 &clubs;','8 &diams;','8 &spades;','9 &hearts;','9 &clubs;','9 &diams;','9 &spades;','10 &hearts;','10 &clubs;','10 &diams;','10 &spades;','Jack &hearts;','Jack &clubs;','Jack &diams;','Jack &spades;','Queen &hearts;','Queen &clubs;','Queen &diams;','Queen &spades;','King &hearts;','King &clubs;','King &diams;','King &spades;'); 
    
    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 ):

    Code:
    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
    Quote Originally Posted by DJCMBear View Post
    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.

    Quote Originally Posted by Philip M View Post
    No, he wants to deal playing cards.

    http://www.codingforums.com/showthread.php?t=212539
    Yes, that is what Im trying to do, and your card shuffler seemed to work. Thank you. Would you mind explaining the - 0.5?
    Last edited by Toxhicide; 12-18-2010 at 07:43 PM.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,247
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Quote Originally Posted by Toxhicide View Post
    . 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.

  • Users who have thanked Philip M for this post:

    Toxhicide (12-18-2010)

  • #13
    New Coder
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •