# Thread: Maths using randomly selected symbols

1. ## Maths using randomly selected symbols

I am randomly selecting the maths symbol (+,-,*,/) using a math.random and then applying the relevant symbol to a variable based on the result, ie if result == 1 then symbolGen = "+"

I now need to use this symbol in the Javascript for it's original purpose, as I have two other numbers being generated and need to work out the answer.

Chris

2. What code do you have so far?

3. Let's go crazy and use functions to perform the operations.

This is not how you would do it for a class where you're supposed to lean about other things, but it could be instructive in other ways.

Code javascript:
```var add = function (a, b) {
return a + b;
},
subtract = function (a, b) {
return a - b;
},
multiply = function (a, b) {
return a * b;
},
divide = function (a, b) {
return a / b;
},
operations = [
{symbol: '-', fn: subtract},
{symbol: '*', fn: multiply},
{symbol: '/', fn: divide}
],
i,
type,
operation,
a,
b,
result = '';
for (i = 0; i < 10; i += 1) {
type = Math.floor(Math.random() * operations.length, 10);
operation = operations[type];
a = Math.floor(Math.random() * 10);
b = Math.floor(Math.random() * 10);
result += a + ' ' + operation.symbol + ' ' + b + ' = ' + operation.fn(a, b) + '\n';
}

4. Firstly, thank you for the swift replies. Secondly, unfortunately I am not overly confident in Javascript so I am somewhat overwhelmed by your reply pmw57. The code I have so far is...

Code:
```var firstNo = Math.floor(Math.random() * 12+1);
var secondNo = Math.floor(Math.random() * 12 + 1);
var mathsSymbol = "";
var symbolGen = Math.floor(Math.random() * 4 + 1);
var completeEquation;

if (symbolGen == 1) {
mathsSymbol = "+";
} else if (symbolGen == 2) {
mathsSymbol = "-";
} else if (symbolGen == 3) {
mathsSymbol = "*";
} else {
mathsSymbol = "/";
}

answer = firstNo + mathsSymbol.hasOwnProperty + secondNo;

completeEquation = firstNo + " " + mathsSymbol + " " + secondNo + " =  " + answer;

var question = document.getElementById('equation');
question.innerHTML = completeEquation;```
Do you think you could possibly explain a method of modifying the code to incorporate your answer. It was very good but I need some help understanding it.

Many thanks,

Chris

5. There is only one way to move on from where you are, and that is to use the eval method to evaluate the result of a string.

However, eval is considered evil so it is better to use other techniques.

For example, this would work with your existing code:

Code javascript:
```if (symbolGen == 1) {
} else if (symbolGen == 2) {
} else if (symbolGen == 3) {
} else {
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•