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
  • 9,710
  • 9
  • 31
  • 66

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
  • 372,613
  • 87
  • 782
  • 758
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
  • 66,980
  • 10
  • 72
  • 94