This is my homework. I can't figure it out with an algorithm. Please help me. It's better to use C++/C.
UPDATE: I'm sorry that I didn't describe this problem clearly. vivek_23: "I have assumed you meant to use 8 as is and use +,-,*,/ between them and not attaching 8's with each other to have numbers like 88,888,8888 etc." What he said is what I mean.
Here is the codes from my friend.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <map>
#include <set>
using namespace std;
const double EPS = 1e-6;
const int NUM = 8;
const int RES = 1000;
double A[NUM];
string res_str[NUM];
set<string> ans;
set<string>::iterator it;
int times = 0;
bool dfs(int n)
{
// 退出条件
if (n==1)
{
if (fabs(A[0]-RES)<EPS)
{
// cout << res_str[0] << endl;
ans.insert(res_str[0]);
}
}
double a, b;
string expa, expb;
map<int ,int> hash;
hash.clear();
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
{
times++;
// 保存状态(操作数i,j)
a = A[i];
b = A[j];
expa = res_str[i];
expb = res_str[j];
//hash判重
if(hash[a] == b) continue;
if(hash[b] == a) continue;
hash[a] = b;
// 改变状态
A[j] = A[n-1];
res_str[j] = res_str[n-1];
// +
A[i] = a+b;
res_str[i] = '(' + expa + '+' + expb + ')';
if (dfs(n-1))
return true;
// -
A[i] = a-b;
res_str[i] = '(' + expa + '-' + expb + ')';
if (dfs(n-1))
return true;
// - 反方向
A[i] = b-a;
res_str[i] = '(' + expb + '-' + expa + ')';
if (dfs(n-1))
return true;
// *
A[i] = a*b;
res_str[i] = '(' + expa + '*' + expb + ')';
if (dfs(n-1))
return true;
// /
if (b!=0)
{
A[i] = a/b;
res_str[i] = '(' + expa + '/' + expb + ')';
if (dfs(n-1))
return true;
}
// /反方向
if (a!=0)
{
A[i] = b/a;
res_str[i] = '(' + expb + '/' + expa + ')';
if (dfs(n-1))
return true;
}
// 恢复状态
A[i] = a;
A[j] = b;
res_str[i] = expa;
res_str[j] = expb;
}
return false;
}
int main()
{
for (int i=0; i<NUM; i++)
{
A[i] = 8;
char c[10];
sprintf(c,"%.0f",A[i]);
res_str[i] = c;
}
cout<<"开始搜索"<<endl;
clock_t start = clock();
dfs(NUM);
for(it = ans.begin(); it != ans.end();it ++)
{
cout<<*it<<endl;
}
}