A random number between 1 and 4 that's not another random number

后端 未结 6 1287
失恋的感觉
失恋的感觉 2021-01-17 05:47

For some reason the following code doesn\'t work.

var a1 = Math.floor(Math.random()*4+1); 

//Answer2
for(a2 = 0; a2 != a1 && a2 != 0; a2 = Math.floo         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 06:24

    There are two standard ways of doing this kind of thing. I'm considering a slightly more general framework though

    Sample from a filtered list

    1. Create the array of base values to select from

      var values = [1,2,3,4]
      
    2. Remove the values you're not interested in

      values = Array.filter( values, function(x) { return x!=a1; } )
      
    3. Select a value at random from the list

      var a2 = values[Math.floor(Math.random()*values.length)];
      

    Use rejection sampling

    1. Create the array of values to select

       var values = [1,2,3,4]
      
    2. Select a value at random and retry until it succeeds

       var a2 =  values[Math.floor(Math.random()*values.length)];
       while( a2==a1 )
       {
         a2 = values[Math.floor(Math.random()*values.length)];
       }
      

    Comparison

    If we consider n to be the length of the initial list and m to be the number of elements removed, then the filtered version does n comparisons to build the filtered list of length n-m, but only one random number generation. In comparison the rejection method does on average n/(n-m) comparisons and random number generations.

提交回复
热议问题