Thread: converting strings to functions

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    104

    converting strings to functions

    Is it possible to convert a string to a function?
    If so, how?
    A simple snippet would be helpful.
    Thanks.

  2. #2
    huh? Why would you want to do this?

  3. #3
    5|-|1+|-|34|) ober's Avatar
    Join Date
    Aug 2001
    Posts
    4,429
    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.

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    104
    <... explain yourself better..>
    OK, if I have:
    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;
    The problem is that I'm given a string of numbers "123".
    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.-
    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 
    }
    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?
    Last edited by kes103; 01-23-2003 at 12:53 PM.

  5. #5
    5|-|1+|-|34|) ober's Avatar
    Join Date
    Aug 2001
    Posts
    4,429
    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.

  6. #6
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    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.

  7. #7
    Registered User
    Join Date
    Dec 2001
    Posts
    104
    See changes make to my second post above.

  8. #8
    Registered User codingmaster's Avatar
    Join Date
    Sep 2002
    Posts
    309

    Exclamation

    U cannot convert strings into functions!!!

  9. #9
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    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.

  10. #10
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728

  11. #11
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    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()
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  12. #12
    Registered User
    Join Date
    Dec 2001
    Posts
    104
    Thanks, PJYelton!

    SilentStrike, is Java considered to be a scripting language?

  13. #13
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    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.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  14. #14
    Registered User
    Join Date
    Dec 2001
    Posts
    104
    SilentStrike, what about C#?

  15. #15
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>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*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting MSVC7 to MSVC8 strings
    By goldwing in forum C++ Programming
    Replies: 3
    Last Post: 10-02-2008, 04:13 PM
  2. Returning strings from functions
    By bobthebullet990 in forum C Programming
    Replies: 2
    Last Post: 08-31-2007, 09:07 AM
  3. passing strings from functions as the "return" part
    By fraktal in forum C Programming
    Replies: 8
    Last Post: 12-13-2005, 01:38 AM
  4. need help with strings and str functions
    By Brokn in forum C Programming
    Replies: 7
    Last Post: 11-12-2005, 10:45 AM
  5. converting a vector of strings into an array.
    By LightsOut06 in forum C++ Programming
    Replies: 2
    Last Post: 10-27-2005, 07:14 PM