Better code to solve number puzzle [duplicate]

Question:

(34 O 5 O 6 O 8 O 9 O 1) O 2=2008

Replace the Symbol of "O" to "+" or "-" or "*",and make the expression is true.

My solution:

info = {{"+"}, {"-"}, {"*"}};

For[a = 1, a < 4, a++,
For[b = 1, b < 4, b++,
For[c = 1, c < 4, c++,
For[d = 1, d < 4, d++,
For[e = 1, e < 4, e++,
For[f = 1, f < 4, f++,
temp = StringJoin["(34", Part[info, a], "5", Part[info, b], "6",
Part[info, c], "8", Part[info, d], "9", Part[info, e], "1)",
Part[info, f], "2"];
If[ToExpression[temp] == 2008, Print[temp]]
]
]
]
]
]
]

The results:

(34*5*6-8-9+1)*2==2008

marked as duplicate by m_goldberg, Kuba♦, Sjoerd C. de Vries, rcollyer, Yves KlettAug 1 '13 at 13:26

Method1:

Select[ToString@StringForm["(3456891)2", ##] & @@@
Tuples[{"+", "-", "×"}, 6], ToExpression[#] == 2008 &]

Select[StringJoin@Riffle[{"(34", "5", "6", "8", "9", "1)", "2"}, #] & /@
Tuples[{"+", "-", "*"}, 6], ToExpression[#] == 2008 &]

(*{"(34×5×6-8-9+1)×2"}*)

Method2:

ClearAll[fun];
fun[{{a_, b_, c_, d_, e_, f_, g_}, {f1_, f2_, f3_, f4_, f5_, f6_}}] :=
HoldForm[(a~f1~b~f2~c~f3~d~f4~e~f5~f)~f6~g];

Select[fun[{{34, 5, 6, 8, 9, 1, 2}, #}] & /@
Tuples[{Plus, Subtract, Times}, 6], ReleaseHold[#] == 2008 &]

(*{((((34×5) 6-8)-9)+1) 2}*)

The following method stops after first solution is found:

I have replaced O with s to make it clearer:

string = "(34 s 5 s 6 s 8 s 9 s 1) s 2 == 2008";
ss = StringCount[string, " s "];
operations = {"+", "-", "*"};
tup = Tuples[operations, ss];
pos = StringPosition[string, " s "];

Do[
With[{str = StringReplacePart[string, tup[[ i]], pos]},
If[
str // ToExpression,
Print[str]; Break[];
]
],
{i, Length@tup}]
(34*5*6-8-9+1)*2 == 2008

Here is an approach:

s = "(34 O 5 O 6 O 8 O 9 O 1) O 2";
ss = StringSplit[s, "O"];
tup = Tuples[{"*", "-", "+"}, 6];
sj[u_]:=StringJoin@Riffle[ss,u];
results = {#, ToExpression@sj[#]} & /@ tup;
ans = (sj[Select[results, #[] == 2008 &][[1, 1]]]) <> " == 2008"

yields:

(34 * 5 * 6 - 8 - 9 + 1) * 2 == 2008

This also works:

s = "(34 O 5 O 6 O 8 O 9 O 1) O 2 == 2008";
ss = StringSplit[s, "O"];
tup = Tuples[{"*", "-", "+"}, 6];
sj[u_] := StringJoin@Riffle[ss, u];
results = {#, ToExpression@sj[#]} & /@ tup;
ans = sj[Select[results, #[] == True &][[1, 1]]]
• Comment: it should be noted that the above worked somewhat fortuitously as there was only one solution. If a similar problem had more than one then the answer could be expressed as Column@(sj/@Select[results, #[] == True &][[All, 1]]). Further, 6 was a manual count but could be replaced by StringCount[s,"O"] – ubpdqn Aug 1 '13 at 12:41