日期:2014-05-19  浏览次数:20851 次

如何拿算24点?
很苦恼,感到一筹莫展,4个从1到9的数,四则混合运算。可以用括号,若能得到24,输出。
      请高手讲个算法。
问题是有括号
比如(3+3/7)×7=24

------解决方案--------------------
#region 24点算法
/*
* Count24(3,3,7,7)
*/

private string[] countMethod = new string[]{ "+ ", "- ", "* ", "/ "};
private int[] countNum;
private int[] countNumBak;

public string Count24(int a,int b,int c,int d)
{
countNumBak = new int[4]{a,b,c,d};
countNum = new int[4];
string result = "没有找到合适的方法 ";
bool isTrue;

//把 abcd 四个数字随机付给数组 countNum
for(int i=0;i <4;i++)
{
countNum[0] = countNumBak[i];
for(int j=0;j <4;j++)
{
if(j==i)
continue;
countNum[1] = countNumBak[j];
for(int k=0;k <4;k++)
{
if(k==j || k==i)
continue;
countNum[2] = countNumBak[k];
countNum[3] = countNumBak[1+2+3 - i-j-k];

result = countMain24(countNum,out isTrue);
if(isTrue)
return result;
else
result = "没有找到合适的方法 ";
}
}
}

return result;
}

private string countMain24(int[] countNum,out bool isTrue)
{
string result = " ";
float countValue = 0;
float countValueBak = 0;
isTrue = false;
float upValueA,upValueBakA;
float upValueB,upValueBakB;

// a (方法) b (方法) c (方法) d
for(int i=0;i <4;i++)
{ //不必计算 b/a 的情况,数组重排列中会计算到此种情况
if(countMethod[i] == "/ " && countNum[1] == 0)
countValue = (float)countNum[0];
else
countValue = eval(countMethod[i],(float)countNum[0],(float)countNum[1]);

upValueA = countValue;
upValueBakA = countValue;

for(int j=0;j <4;j++)
{
//第一种情况 (a和b的结果) (方法) c
if(countMethod[j] == "/ " && countNum[2] == 0)
{}
else
{
countValue = eval(countMethod[j],upValueA,(float)countNum[2]);
}

//第二种情况 c (方法) (a和b的结果)
if(countMethod[j] == "/ " && upValueBakA == 0)
{
countValueBak = upValueBakA;
}
else
{
countValueBak = eval(countMethod[j],(float)countNum[2],upValueBakA);
}

upValueB = countValue;
upValueBakB = countValueBak;

for(int k=0;k <4;k++)
{
//第一种情况 d (方法) (a,b,c的结果1)
if(countMethod[k] == "/ " && upValueB == 0)
{}
else
{
countValue = eval(countMethod[k],(float)countNum[3],upValueB);
if(Math.Round(countValue,4) == 24)
{//如果已经得到24点,则结束本程序
result = countNum[3].ToString() + countMethod[k] + "(( "+countNum[0].ToString() + countMethod[i] + countNum[1].ToString()+ ") ";
result += countMethod[j] + countNum[2].ToString() + ") ";
result += " = 24 ";
isTrue = true;
return result;
}
}

//第二种情况 (a,b,c的结果1) (方法) d
if(countMethod[k] == "/ " && countNum[3] == 0)
{}
else
{
countValue = eval(countMethod[k],upValueB,(float)countNum[3]);
if(Math.Round(countValue,4) == 24)
{//如果已经得到24点,则结束本程序
result = "(( "+countNum[0].ToString() + countMethod[i] + countNum[1].ToString()+ ") ";