fork download
  1. #!/usr/bin/env ruby
  2.  
  3. #The recursive function to find out all the expressions which evaluate to a given value
  4. #The technique used is "backtracking"
  5.  
  6. def findExpr(s, expr, k)
  7. if s.length != 0
  8. expr += s[0].chr
  9. val = eval(expr)
  10.  
  11. if val == k && s.length == 1
  12. print expr, "\n"
  13. elsif val < k
  14. #The operations supported are '*', '+' and '.'
  15. #where '.' is simple concatenation of the digits
  16. findExpr(s[1..-1], expr + '*', k)
  17. findExpr(s[1..-1], expr + '+', k)
  18. findExpr(s[1..-1], expr, k)
  19. end
  20. end
  21. end
  22.  
  23.  
  24. findExpr("123456789", "", 2097)
  25.  
  26. stringy="123456789"
  27. subs = stringy[1..-1];
  28. puts #{subs}
Success #stdin #stdout 0.08s 4888KB
stdin
Standard input is empty
stdout
1+2+345*6+7+8+9
12*3*45+6*78+9
12*34+5*6*7*8+9