1

I try to generate number of year randomly.

But I can't get the result what I expected.

This is my sample code.

function getNumber(start, end) {
  return Math.floor(Math.random() * end) + start;
}

function generate(n){
  var result = [];
  for(let i = 0; i < n; i++){
    let YEAR = getNumber(1900,2018);
    result.push(YEAR);
  }
  /* I want to see the number 1900 ~ 2018 */
  console.log(result);
}
generate(10); 

I want to get the number between 1900 and 2018 but I can't.

How can I get the number what I want?

kyun
  • 8,693
  • 8
  • 27
  • 56

2 Answers2

5

You're adding to start a number which can be up to end (minus one). What you need it is to be up to end-start.

Just change

return Math.floor(Math.random() * end) + start;

to

return Math.floor(Math.random() * (end-start)) + start;
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726
2

You were almost there, just make it

Math.random() * (end-start)

instead of

Math.random() * end

Demo

function getNumber(start, end) {
  return Math.floor(Math.random() * (end-start)) + start;
}

function generate(n){
  var result = [];
  for(let i = 0; i < n; i++){
    let YEAR = getNumber(1900,2018);
    result.push(YEAR);
  }
  /* I want to see the number 1900 ~ 2018 */
  console.log(result);
}
generate(10); 
gurvinder372
  • 64,240
  • 8
  • 67
  • 88