Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if number is "between" values?

Tags:

javascript

// beginner learning Js in a program I was asked to start work on a Rock, Paper, Scissors game this is the code I made, but the computer always choses scissors!? any idea why? any help would be awesome!

  1. If computerChoice is between 0 and 0.33, make computerChoice equal to "rock".

  2. If computerChoice is between 0.34 and 0.66, make computerChoice equal to "paper".

  3. If computerChoice is between 0.67 and 1, make computerChoice equal to "scissors".

var userChoice = prompt ("Do you choose rock, paper or scissors?");

var computerChoice = Math.random();

if (computerChoice === (0 , 0.33)) {
    console.log("rock");
} else if (computerChoice === (0.34 , 0.66)) {
    console.log("paper");
} else {
    console.log("scissors");
}
like image 374
user3599708 Avatar asked Jan 10 '23 16:01

user3599708


1 Answers

First off, you can't just make up syntax - it Just Doesn't Work. Programming is about the application of existing rules, where most rules are not your own.

In JavaScript, due to the comma-operator, x === (a, b) is semantically equivalent to x === b (when the a expression has no side-effects), so that clearly won't work. In the original code this ensured that none of the first two conditions (e.g choice === 0.33) ever matched - so the default/else of "scissors" was always chosen.

While the general way to check an inclusive range is x >= a && x <= b, we can do one better than this by relying on the ordering of if conditional evaluation and "inchworming" through an expanding range.

if (choice <= 1/3) {
  console.log("rock");
} else if (choice <= 2/3) { /* choice > 1/3, per above */
  console.log("paper");
} else {                    /* choice > 2/3, per above */
  console.log("scissors");
}

Alternatively, we could also get a discreet random integer back,

/* get a random number 1, 2, or 3 */
var choice = Math.floor(Math.random() * 3 + 1);

and then direct equality without a range check can be used

if (choice === 1) {
  console.log("rock");
} else if (choice === 2) {
  console.log("paper");
} else { /* choice === 3 */
  console.log("scissors");
}
like image 161
user2864740 Avatar answered Jan 22 '23 04:01

user2864740