2

I want to generate a random number using 0 and 1.

I've written the code, but the larger the number, the larger the error range. How can I write better code?

My current code

Code to generate 0 and 1

const get_zero_or_one = () => {
  return Math.floor(Math.random() * (2))
}

Code to generate a random number using the above code

The code I want to change is this code.

const RandomResult = (max_number) => {
    let answer = 0;
    for (let i = 0; i < max_number -1; i++) {
        answer += get_zero_or_one()
    }
    return answer
}

The condition is not to use the Math.random function. Thanks!

조흐긴
  • 59
  • 1
  • 7
  • 2
    What do you mean by "the larger the number, the larger the error range"? do you have errors using `Math.random`? And why the condition not to use it? A code challenge or some obscure homeworks question? – Kaddath Jan 30 '19 at 13:50
  • `const get_zero_or_one = () => 0;` (I chose 0 randomly, a variant on https://xkcd.com/221/) – Pac0 Jan 30 '19 at 13:52
  • hmm.. In the get_zero_or_one described above, we want to use the Math.random function and create a random function using this get_zero_or_one. – 조흐긴 Jan 30 '19 at 13:55
  • It is a code challenge found in Korea. The method I presented is that I heard that there are good ways to think that losing the meaning of random values ​​in the case of a larger number (ex: 100, 1000). – 조흐긴 Jan 30 '19 at 13:57
  • Typical approach is to use a Linear Congruential Generator, as long as you're not using it for cryptographic security: https://en.wikipedia.org/wiki/Linear_congruential_generator – Duncan Thacker Jan 30 '19 at 14:00
  • You could look into this book The Art of Computer Programming, Volume 2: Seminumerical Algorithms from Donald E Knuth for various algorithm available to generate random numbers. – Eponyme Web Jan 30 '19 at 14:21

1 Answers1

-2

The idea is simple i get the current date by new Date() and use get its milliseconds and then check if its even then return 0 else 1

const get_zero_or_one = () => {
  return (((new Date()).getMilliseconds()) % 2 === 0) ? 0 : 1;
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73