Is the algorithm correct? [closed]

-4

I made this code to test a random number:

function a(n){
  var b = (Math.floor(Math.random() * (parseInt(n) - n/4) + n/4));
  
  return b;
}

console.log(a(20));

My question is if all the numbers have the same opportunity to leave, and how can I check it?

Since trying it out I did not get any 10 more than 20 times

    
asked by Eduardo Sebastian 02.09.2017 в 00:15
source

2 answers

1

To try you can do a function like the following and you can get the statistics you need

function a(n){
  var b = (Math.floor(Math.random() * (parseInt(n) - n/4) + n/4));
  
  return b;
}

function test(){

  var cont=1;
  var numero = parseInt($("#busca").val(), 10);
  var n = parseInt($("#n").val(), 10);
  var random;
  var encontrado = false;
  var limite = parseInt($("#limite").val(), 10);

  do{
  random = a(n);
  console.log(cont+". "+random);
  if(random==numero){
    encontrado=true;
    break;
    }
  }while(cont++ <= limite)

  if(encontrado)
    console.log("Ya salio el numero " + numero);
  else
    console.log("No salio el numero " + numero);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

N:<input type="text" id="n" value="20"><br>
Esperar: <input type="text" id="busca" value="10"><br>
Iteraciones: <input type="text" id="limite" value="50">
<input type="button" onclick="test();" value="Test" />
    
answered by 02.09.2017 в 01:33
1

According to this :

  

random ()

     

Returns to Number with positive sign, greater than or   equal to 0 but less than 1, chosen randomly or pseudo randomly with   approximately uniform distribution over that range, using an   implementation-dependent algorithm or strategy. This function takes no   arguments.

That is, the probability of any number within the range 0 to 1 (not including 1) follows an approximate uniform distribution, which means that any number should have the same probability of appearing. While it may seem obvious, this does not mean that executing your algorithm a certain number of times, you will surely get a certain number, it means that as you continue executing it (that is, your attempts tend to infinity), the apparitions of each number should tend to be the same.

    
answered by 02.09.2017 в 16:25