Zutru - 1 year ago 58

Android Question

I'm currently working on a school project in Android Studio.

I want to write an algorithm which generates randomly equations, not just random numbers but actual equations like 30+48-18.

I was thinking of the following steps:

- Generate a random number which indicates the amount of operations with an interval from 1 to 3. (I've allready written that code:

`Random rand1 = new Random();`

int operation = rand1.nextInt(2)+1;

String StringOperation = String.valueOf(operation);

- Then for every operation randomly choose which operation (+,-,*,/). I'm struggeling to write the code for this step...
- The final step would be to randomly generate the acutal numbers which will appear in the actual equation. This would mean that you need (amount of operations)+1 numbers for the equation. This wouldn't be so hard to write the code for.

It would help me a lot if someone could help me with step 2 as I'm struggling to write the code for this step. I've already tried a few things but they all didn't work.

If anything is unclear, please write it so I can clarify the problems :)

Thank you already in advance!

Answer Source

Then for every operation randomly choose which operation (+,-,*,/). I'm struggling to write the code for this step...

In your finite operation set {+,-,*,/}, how would you randomly select the operation as a human? You would pick randomly by looking at their positions right? So the hint is to use randomly choose the position in the range(0,3) and use the random position as an index to get the operation.

Try this without reading further.

```
String[] operationSet = new String[]{"+", "-", "/", "*"};
public void testGenerateRandomEquations() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(3)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(Integer.MAX_VALUE) - random.nextInt(Integer.MAX_VALUE);
numbers.add(number);
}
//Now you've the list of random numbers and operations. You can further randomize
//by randomly choosing the number and operation from those list.
}
```