Search code examples
algorithmfunctiondata-structurespseudocode

Generating random functions (not numbers!) - How to implement


I need to generate random functions. For example, if I have a function set F={sin, cos} and a variable set V={x, y}, I should be able to produce functions like following:

  • f_1(x,y)=sin(x)
  • f_2(x,y)=cos(y)
  • f_3(x,y)=sin(x) + cos(y)
  • f_4(x,y)=sin(x**2)-3xcos(xy)

What would I need to use (Data structure, algorithm etc.)? I'm open to your ideas and advice.


Solution

  • Consider your set of functions, possible variable name (e.g. 'x', 'y') and operators +, -, *, **, (,) etc. as an alphabet. Construct a grammar for the valid expressions. Construct a corresponding state machine that produces sentences of your expression language on transition sequences from start node to end node. Implement the state machine to follow a random branch at each node. Voila ...

    Ask further questions in comments to this answer if necessary