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

后端 未结 6 1289
失恋的感觉
失恋的感觉 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:22

    Try with this function. It'll give you an array with numbers from 1 to max in random order. Then you can use it to assign a value to a variable and it'll never repeat:

    Edit: I found a purely functional way to do it:

    function randomRange(min, max) {
      return (new Array(++max-min))
        .join('.').split('.')
        .map(function(v,i){ return min+i })
        .sort(function(){ return 0|Math.random()*max });
    }
    
    console.log(rand(1,4)); //-> [4,2,1,3] random array from 1 to 4
    
    var arr = rand(1,4);
    var a = arr[0];
    var b = arr[1];
    ...
    

    Edit 2: Seems like the above has problems with some browsers, check out Random but just in Chrome for a better solution.

    Demo: http://jsbin.com/ohohum/1/edit (run multiple times to see the randomness)

提交回复
热议问题