0

I need a way to randomise an input math equation (mainly their coefficients).

So for example "x+y-ze^5" could be randomized into "x-y+2ze^4" or "2x+y-3z*e^4".

I am doing this in rails at the moment, and one of the main issues I have is that I can only store equations in strings rather than a math object. How do I do this? Is there any gems or API's I can use? I would also need to use this with Latex input equations. I have used latex API's but I have only found ones that can display equations, not those that turn strings into usable and modifiable math equations.

For example if I input "x+y+z", it should get randomized into "x-y+2ze^4".

Similarly if I give it "x'+sin(x/2)-Integral(xdx)", it could get randomized into "2x'-sin(x/4)-Integral(2xdx)". The idea here the function can take any equation I give it and randomise it's coefficients.

Railroad Tycoon
  • 147
  • 2
  • 10
  • 1
    You might want to take a look at [How to get a random number in Ruby](https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby). Along with `string interpolation`, you should be well on the way to getting the strings you're looking for. Now, whether you can actually *use* those strings is another matter. – jvillian Apr 20 '18 at 22:43

1 Answers1

1

Not pretty but should be close to what you want

def random_coef
  op1 = ['+','-'].sample
  op2 = op1 == '+' ? '-' : '+'
    "#{[1,2].sample}x #{op1} y #{op2} #{[1,2,3].sample}ze ^ #{[4,5].sample}".gsub(' ','')
end

10.times { puts random_coef}
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48