Home > Net >  Randomly choose between of , -, or * and apply it to two numbers
Randomly choose between of , -, or * and apply it to two numbers

Time:10-03

Good day

I am new to java and would like to know if there is a way for me to randomly choose between multiplication and addition and apply it to two numbers.

Any guidance would be appreciated.

CodePudding user response:

I guess a code like the following could work:

// given two number a, b

double rand = Math.random();
if (rand > 0.5)
   c = a*b;
else
   c = a b;

// c is the result of the addition/multiplication

CodePudding user response:

You can put all the possible operations in a List as BinaryOperators, then choose a random index each time.

List<BinaryOperator<Integer>> ops = List.of(Integer::sum, (a,b)->a-b, (a,b)->a*b);
int a = 1, b = 2; // numbers to apply operator to
int result = ops.get(ThreadLocalRandom.current().nextInt(ops.size())).apply(a, b);
System.out.println(result);

CodePudding user response:

Place the operators into an array and select a random index value for that array:

String[] operators = {" ", "-", "*", "/"};
int randomOperatorIndex = new java.util.Random().nextInt(operators.length);
int num1 = 24;
int num2 = 12;
double ans = 0.0d;
switch (randomOperatorIndex) {
    case 0:   //   
        ans = num1   num2;
        break;
    case 1:   // - 
        ans = num1 - num2;
        break;
    case 2:   // * 
        ans = num1 * num2;
        break;
    case 3:   // / 
        ans = num1 / num2;
        break;
}
 
System.out.println(num1   " "   operators[randomOperatorIndex] 
                     " "   num2   " = "   ans);
  • Related