Is it possible to convert a string to a function?
If so, how?
A simple snippet would be helpful.
Thanks.
This is a discussion on converting strings to functions within the C++ Programming forums, part of the General Programming Boards category; Is it possible to convert a string to a function? If so, how? A simple snippet would be helpful. Thanks....
Is it possible to convert a string to a function?
If so, how?
A simple snippet would be helpful.
Thanks.
convert a string to a function...
No.
Maybe if you explained yourself a little better, that might actually make sense.
EntropySink. You know you have to click it.
<... explain yourself better..>
OK, if I have:
The problem is that I'm given a string of numbers "123".Code:string sf1="1+2-3"; string sf2="1-2+3"; // maybe I'll make these arrays of functions // how do I take sf1 and sf2 usable functions? f1=sf1; f2=sf2;
I must find out how many different combinations of '+' and '-'
will be less than or equal to a target number say '9'.
I can easily insert spaces or even '+' or '-' between the
numbers.
eg.-
now the only problem is to change the numbers back to integers and the '+' and '-' back to operators. I can use strtol to convert the integer characters to integers, but how do I conbert the '+' and '-' to operators?Code:string sf1="123",sf2,sf3; int noNumbs=0; noNumbs=sf1.size(); for(int i=0; i<noNumbs-1; i++){ sf2=sf1[i]+"+"; // or something like this }
Last edited by kes103; 01-23-2003 at 12:53 PM.
I'm still confused. You cannot make a function out of a string. Now if you wanted to make an array of strings, that would be something different altogether.
EntropySink. You know you have to click it.
C++ is compiled, it has no eval() function, (like in perl). Parsing and evaluating expressions in your strings would have to be done by hand. Doing so is quite beyond the scope of what can be easily taught over a message board.
See changes make to my second post above.
You'll need to parse the string to get your results. One way is to use a recursive function, and I've written this problem once this way but I need to find it first before I can show it.
Another way if double digits are not allowed (ie "123" cannot be 12-3) is to parse the digits into a vector or array, then use those numbers to solve the problem and not worry about the string anymore.
check out this thread:
address of substring
I programmed something like that in python. (given a set of numbers, find some sequence of operations on the given numbers (+ - * /) that produces the answer 24). If you are not dead set on C/C++ for this problem, 'scripting' langauges (python, perl, etc) offer much cleaner solutions to this problem.
Basically, the problem breaks down into enumerating all possibilities (somewhat easier with scripting langauge with builtin lists), and then testing them all with eval (non-existant in C++).
The python code for my somewhat similiar problem is below, I don't know if it will help, however.
Code:import probstat import time QUESTION=0 START_GAME=1 END_GAME=2 OTHER_TYPE=3 def identify_line(line): """ Identifies a line of IRC text as either a QUESTION, START_GAME, END_GAME or OTHER_TYPE """ splitlines = line.split(' ') if len(splitlines) == 15: question_test = "Calculate 24 with + - * / () and the numbers".split(' ') for i in range(11): if splitlines[i] != question_test[i]: return OTHER_TYPE return QUESTION elif len(splitlines) == 11: if line == "Starting a game with 5 turns to win needed to win": return START_GAME elif line[0:3] == '-=-' and line[-3:] == '-=-': return END_GAME return OTHER_TYPE def solve_24line(line): """ Solve line from 24 bot. Assumes line is valid question, and does no checking """ splitlines = line.split(' ') target = 24 numlist = [] try: for i in range(1,5): numlist.append(float(splitlines[-i][0])) except ValueError: return '' return find_solution(numlist, target) def time_test(line): start = time.clock() if identify_line(line) == QUESTION: print solve_24line(line) print time.clock() - start def main(): time_test("Calculate 24 with + - * / () and the numbers 2, 7, 4, 1") time_test("Calculate 24 with + - * / () and the numbers 4, 3, 4, 1") time_test("Calculate 24 with + - * / () and the numbers 6, 2, 8, 2") def build_expr(list_of_num, list_of_ops, cur, dec_format='%f'): """ Assumed len(list_of_num) == len(list_of_ops) + 1 """ if cur==0: return ((dec_format+'%s'+dec_format)) % (list_of_num[1], list_of_ops[0], list_of_num[0]) else: return ((dec_format+'%s(%s)') % (list_of_num[cur+1], list_of_ops[cur], build_expr(list_of_num, list_of_ops, cur-1, dec_format))) def find_solution(numlist, target, operators="+-*/", dec_format="%d"): """ Return an expression as a string containing every number in numlist using only the basic arithmetic operators (+,-,/,*) and parenthesis that evaulates to target, else return "" """ # there are n - 1 binary operators for n numbers all_op_possibilities = direct_product(operators, len(numlist)-1) for oper_seq in all_op_possibilities: for (num_seq) in probstat.Permutation(numlist): # build and evaluate the function with floats, so the non C based division isn't used # IE, the bot thinks 7/3 is not 2, but rather 2 and 1/3... lame bot :) # The work around is to calculate with floats, use some small range for error # and see if the expression is within the error. float_expr = build_expr(num_seq, oper_seq, len(oper_seq)-1) try: float_result = eval(float_expr) if float_result > target - .1 and float_result < target + .1: return build_expr(num_seq, oper_seq, len(oper_seq)-1, dec_format) except ZeroDivisionError: pass return "" def direct_product(source,seq_len): """ Return list of sequence containing all possible 'enumerations' of list with the given components. The returned list will contain len(source)^seq_len sublists of length seq_len IE. direct_product([1,2],2) should return [[1, 1], [1, 2], [2, 1], [2, 2]] """ if seq_len == 1: return [[item] for item in source] else: sub_product = direct_product(source, seq_len-1) return [[item]+tail for item in source for tail in sub_product] if __name__ == '__main__': main()
Thanks, PJYelton!
SilentStrike, is Java considered to be a scripting language?
Well, apparently, Java has no eval.
http://mindprod.com/jglosseval.html
Writing your own eval is likely harder than any other part of the solution.
SilentStrike, what about C#?
>>Is it possible to convert a string to a function?
Not in C++, why not use a language that makes such a feat trivial...Perl comes to mind. :-)
Code:#!usr/bin/perl -w print "Enter a function: "; chomp($sfunc = <STDIN>); print eval $sfunc, "\n";
*Cela*