SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    random number generating

    how can i create a random number that is in between multiple variables. for example 0-10, 100-110.

    it can be in between either of the two options but no greater or less

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    If you have multiple ranges, put them in an array: 
    var arr=[[0,5],[100,105]];
    
    get a random index of the array:
    
    r=arr[Math.floor(Math.random()*arr.length)],
    min=r[0], max=r[1];
    
    then generate the random number from the selected range.
    
    Math.floor(Math.random()*(max-min+1)+min)

  3. #3
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This code is working in Konqueror 4.5.5 and Firefox 4.0b9
    Code:
      
    <script type="text/javascript">
    
    var A =[ [0,10], [100,110]];
    var t = String(new Date().getTime()).slice(this.length-2);
    alert(t);
    
    var r = A[Math.floor(Math.random()*A.length)];
    var min=r[0];
    var max=r[1];
    var mod = max - min + 1;
    var kalan = Number(t) % mod;
    var result = min + kalan;
    alert(result);
    
    </script>
    Bismillahirrahmanirrahîm
    Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

  4. #4
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    without using Math.random
    Code:
      
    <script type="text/javascript">
    
    var A =[ [0,10], [100,110]];
    var s = String(new Date().getTime());
    var d = s.slice(this.length-1); 
    alert(d);
    var t=  s.slice(this.length-2); 
    alert(t);
    
    var r = A[ Number(d) % A.length];
    alert(r);
    var min=r[0];
    var max=r[1];
    var mod = max - min + 1;
    var kalan = Number(t) % mod;
    var result = min + kalan;
    alert(result);
    
    </script>
    Bismillahirrahmanirrahîm
    Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.


Bookmarks

Posting Permissions

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