- Home /
calculate terms in runtime
Is there an easy way to get the result of a mathematical term in runtime?
For example I randomly genrate a term like 1+3*4=, the player has to type in the correct result an the game says right or wrong. Is there a function like
result = Calculate(term:string);
Any ideas???
I think there's no predefined function for you, it may need you to code for it. If you generate the terms in your own way, then you should know the result already. If you're reading the term from somewhere else, then you need to parse the string and split the string from * and / first, then + and - and so on.
Well the problem is, it ist a learning game for children, that shall figure out the right order of the numbers in the term. there can be be more then one solution. so i have to check, if what they put together is right or wrong
Answer by Eric5h5 · Jul 19, 2012 at 03:12 PM
You can use eval to convert a string into code.
function Start () {
var a = Random.Range(1, 10);
var b = Random.Range(1, 10);
var c = Random.Range(1, 10);
var operations = "-+*";
var equation = "" + a + operations[Random.Range(0, operations.Length)]
+ b + operations[Random.Range(0, operations.Length)] + c;
var x = eval(equation);
Debug.Log (equation + "=" + x);
}
I want to convert my project later to iphone and android. does eval work ther or do i have to create an own function anyway?
No, eval doesn't work with #pragma strict, so therefore not iOS.
Ah thank you - now I have an idea, what pragma strict means ;) That means I have to write my own function to do the calculation ..
Answer by Nightwatch · Jul 19, 2012 at 02:53 PM
Yeah you will have to parse it, build up a tree to apply the calculation order etc.
I would say, if you randomly generate it, do not generate it as string in the first pace, but in your own format you can calculate and just present it as string.
Maybe have custom a function RandomEq(...) and get back the result and the string representation in a struct.
Answer by Piflik · Jul 19, 2012 at 03:02 PM
Completely random might be difficult/impossible, but you could easily build a function that churns out many different terms...
First I would use a Switch statement (and a random number) to choose the general structure of the term, without fixed numbers, only variables. Then you could assign the variables random numbers, calculate the solution and test it against the player's input.
Your answer
Follow this Question
Related Questions
Access a String array in one script from another script 0 Answers
Finding if a specific key contains a specific value in a Hashtable? 1 Answer
Enemy AI Error 1 Answer
String split script 1 Answer