Good time! The task is to randomly get the number 1 or 2. For example, for the game “coin” or “guess what hand”. Math.random in javascript prints from 0 to 1, and then 1 does not. In general, how to get randomly 2 numbers: 1 or 2? Tell me please

  • Add to the result 1. - Andrei Arshinov
  • So: Math.round (Math.random ()) + 1 - Nofate
  • just need to round the number - Valentin Zhukov
  • The jquery tag is correct) By the way, is there really no random.nextBoolean () in js? - kandi

9 answers 9

As an option:

 (Math.random()<.5)+1 

    You can immediately give a general formula for finding random numbers in the desired range:

      //min и max соответственно нужное минимальное и максимальное значение: [min,max] Math.round(Math.random()*(max-min)+min) 
       Math.random() * 2 + 1 | 0 

      Who is shorter?

      • Maybe just in case, explain why? - disfated
      • The decision is revised. The answer is fully consistent with the context of the question, despite its brevity. - AseN

      Answer found

       var ran = 1 + Math.random()*(3-1); ran = Math.floor(ran); 
      • 7
        and perhaps 3 - 1 is not 2? - DreamChild
      • Well, in general, such code gives out only 1 and 0) and it works well - Sasha
      • one
        a thousand and one ways to get randomly 1 or 2 Math.ceil (Math.random () * 2) - zb '26
      • 2
        @eicto, if math.random returns 0, the result will be 0 - mountpoint
      • one
        I think it is better to change the condition to the opposite - that is, var r = Math.random()>0.5?1:2; . After all, to make a comparison on "equal" for real numbers is somehow bad. I specifically tested in nodejs (this is from the v8 engine) - those that are greater than 0.5 and equal to or greater than 0.5 even at 1000kk attempts (a billion) are slightly less (by 50k). - KoVadim

      Math.round (2 - Math.random ())

         console.log( Math.round( Math.random( ) * 1 ) + 1 ); 
           function rand(min, max){ if(max){ return Math.floor(Math.random() * (max - min + 1)) + min; }else{ return Math.floor(Math.random() * (min + 1)); } } alert(rand(1,2)); 
             Math.round( Math.random()) + 1 
            • It is not the answer to the question. To leave comments or ask the author to clarify a question, leave a comment on the question, you can leave any number of comments under your message, and when your reputation reaches the required level, you can comment on any user posts . - AseN
            • @ 0xFFh You thought - disfated
            • @ 0xFFh: this answer may be wrong (you can vote "against"), but this is the answer. - jfs

            For java hipsters:

             System.out.println((System.nanoTime() & 1) + 1);