private const double Precision = 1E-6 ; //
private bool fSearchExpression( double [] ANumbers , string [] AExpressions ,
int ALevel, int ADest, List < string > AResults)
{
bool Result = false ;
if ((ALevel <= 1 ) && ( Math . Abs(ANumbers[ 0 ] - ADest) <= Precision))
{
AResults . Add(AExpressions[ 0 ]);
return true ;
}
for ( int i = 0 ; i < ALevel; i ++ )
for ( int j = i + 1 ; j < ALevel; j ++ )
{
double A = ANumbers[i];
double B = ANumbers[j];
ANumbers[j] = ANumbers[ALevel - 1 ];
string vExpA = AExpressions[i];
string vExpB = AExpressions[j];
AExpressions[j] = AExpressions[ALevel - 1 ];
AExpressions[i] = '(' + vExpA + '+' + vExpB + ')' ;
ANumbers[i] = A + B;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
AExpressions[i] = '(' + vExpA + '-' + vExpB + ')' ;
ANumbers[i] = A - B;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
AExpressions[i] = '(' + vExpB + '-' + vExpA + ')' ;
ANumbers[i] = B - A;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
AExpressions[i] = '(' + vExpA + '*' + vExpB + ')' ;
ANumbers[i] = A * B;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
if (B != 0 )
{
AExpressions[i] = '(' + vExpA + '/' + vExpB + ')' ;
ANumbers[i] = A / B;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
}
if (A != 0 )
{
AExpressions[i] = '(' + vExpB + '/' + vExpA + ')' ;
ANumbers[i] = B / A;
if (fSearchExpression(ANumbers, AExpressions,
ALevel - 1 , ADest, AResults)) Result = true ;
}
ANumbers[i] = A;
ANumbers[j] = B;
AExpressions[i] = vExpA;
AExpressions[j] = vExpB;
}
return Result;
}
private bool SearchExpression( List < string > AResults, int ADest, params int [] ANumbers)
{
double [] vNumbers = new double [ANumbers . Length];
string [] vExpressions = new string [ANumbers . Length];
for ( int i = 0 ; i < ANumbers . Length; i ++ )
{
vNumbers[i] = ANumbers[i];
vExpressions[i] = ANumbers[i] . ToString();
}
return fSearchExpression(vNumbers, vExpressions, ANumbers . Length, ADest, AResults);
}
private void button1_Click( object sender , EventArgs e)
{
List < string > vExpressions = new List < string > ();
SearchExpression(vExpressions, 22 , 1 , 2 , 3 , 4 , 5 );
foreach ( string vExpression in vExpressions)
textBox1 . AppendText(vExpression + "\r\n" );
}