Adam Oates
Adam Oates

Reputation: 313

Is there a way I can make JavaScript choose plus or minus operator?

I want my JavaScript to be able to choose randomly to either subtract using the - operator or add using the + operator. Is there anyway I can make it randomly choose between the two?

Upvotes: 0

Views: 3805

Answers (4)

Nic Scozzaro
Nic Scozzaro

Reputation: 7363

I suggest using the inline syntax with the Math.random() trick that others have mentioned:

var a = 1;
var b = 2;
var a_plusOrMinus_b = (Math.random()<=0.5 ? a+b : a-b);

alert(a_plusOrMinus_b);

Upvotes: 0

Petar Donchev Marinov
Petar Donchev Marinov

Reputation: 81

As @Chizzle said, the way to go is Math.random(), but if you want to be a bit more precise, you should use:

Math.random() <= 0.5

This way the chance is 50 to 50, and the interval could be described by [0,0.5) and [0.5,1). Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).

Here is a simple code snippet with a function:

function randSumSub(a, b) {
  if (Math.random() <= 0.5) {
    result = a - b;
  } else {
    result = a + b;
  }
  return result;
}
#result {
  display: inline-block;
  width: 20px;
  height:20px;
  text-align: center;
  border: 1px solid red;
}
2 +|- 5
<button onclick="document.getElementById('result').innerHTML = randSumSub(2,5);">=</button> 
<div id="result">?</div>

Upvotes: 2

Cymen
Cymen

Reputation: 14429

I would do something like this:

function getSignMultiplier() {
  if (Math.random() < 0.5) {
    return -1;
  } else {
    return 1;
  }
}

Then to use it:

var numbers = [
  5 * getSignMultiplier(),
  5 * getSignMultiplier(),
  5 * getSignMultiplier()
];

document.getElementById('output').innerText = numbers.join(', ');

JSFiddle: https://jsfiddle.net/2snbgyw2/1/

Upvotes: 0

Chizzle
Chizzle

Reputation: 1715

Yes you can.

get a random number

Math.random();

If the random number is less than 0.5, multiply by -1, else do nothing.

Upvotes: 1

Related Questions