Home > Software engineering >  randomly selecting 4 basic math operations
randomly selecting 4 basic math operations

Time:09-19

So, in P5JS, i am trying to create a project, where I input 2 numbers and they are either randomly added, subtracted, multiplied or divided after clicking a button, could someone please show how I would write in JavaScript the code for randomly picking the 4 basic math operations and then the two numbers I inputed are either added, subtracted, multiplied or divided at random once clicking a button?

CodePudding user response:

You can put a random specifier easily:

const randomOpt = Math.floor(Math.random() * 4)

Then, check the randomOpt with a switch and do what you want:

switch(randomOpt) {
  case 0:
    return inputValue1   inputValue2
  case 1:
    // -
  case 2:
    // *
  case 3:
    // /
}

CodePudding user response:

It's quite simple

const operations = {
    '0': (num1, num2) => num1   num2,
    '1': (num1, num2) => num1 - num2,
    '2': (num1, num2) => num1 * num2,
    '3': (num1, num2) => num1 / num2,
}
function randomOperation(num1, num2) {
    return operations[Math.floor(Math.random() * 4)](num1, num2);
}

example

https://codepen.io/alexey-shaposhnikov/pen/MWGmaaX

  • Related