For my computer science 3 class, the professor is having us create a Binary tree that consist of random numbers and random operators. I have the random numbers part working, but getting random operators is kinda tricky. I am trying to use a switch-case statement and an array to randomize the operators, but the syntax of this all is quite tricky. Is there a certain why I should go about writing this? Should I even use a switch-case?
import java.util.Random;
public class TestArithmetic {
public static void main(String[] args) {
Node n = new Plus(new Divide(randConst(), randConst()),
new Divide(randConst(), randConst()));
Node nDivide = new Divide(new Plus(randConst(), randConst()),
new Plus(randConst(), randConst()));
Node nMulti = new Multi(new Plus(randConst(), randConst()),
new Plus(randConst(), randConst()));
Node nMinus = new Minus(new Plus(randConst(), randConst()),
new Plus(randConst(), new Const(4.4)));
System.out.println(n + " = " + n.eval());
System.out.println(nDivide + " = " + nDivide.eval());
System.out.println(nMulti + " = " + nMulti.eval());
System.out.println(nMinus + " = " + nMinus.eval());
}
public static Binop randOp(Node lChild, Node rChild) {
Node[] opArray = {new Plus(), new Minus(), new Multi(), new Divide()};
Random randOpNum = new Random();
int randNumOp1 = randOpNum.nextInt(4);
switch (randNumOp1) {
case 1:
case 2:
case 3:
case 4:
}
return new Binop();
}
public static Const randConst() {
int max = 20;
int min =1;
Random num = new Random();
double randNum = num.nextInt(max-min+1) + min;
return new Const(randNum);
}
You can take advantage of the fact that constructors are simply functions that take some parameters that return an instance of the class in which they are defined.
As such your Binop subclasses constructors can be modeled as BiFunction<Node, Node, ? extends Binop>
// we first initialize an array with reference to all Binop subclasses constructors
private static final List<BiFunction<Node, Node, ? extends Binop>> opArray = new ArrayList<>(){{
opArray.add(Plus::new);
opArray.add(Minus::new);
opArray.add(Multi::new);
opArray.add(Divide::new);
}};
public static Binop randOp(Node lChild, Node rChild) {
Random randOpNum = new Random();
int randNumOp1 = randOpNum.nextInt(opArray.size());
return opArray.get(randNumOp1).apply(lChild, rChild);
}