24-point classic algorithm

Source: Internet
Author: User

1. Overview

Given four integers, each number can only be used once. +-*/() is used to construct an expression, and the result is 24, this is a common 24-point game. There are a lot of programs in this regard, and they are generally used to solve the problem. This article introduces a typical 24-point algorithm, and provides two detailed 24-point programs: process-oriented C implementation and Object-Oriented Java implementation.

2. Basic Principles

The basic principle is to enumerate all the possible expressions of four integers and then evaluate the expressions.

Expression definition: expression = (expression | Number) operator (expression | number)

Because the four operators +-*/can be used are all 2-element operators, this article only considers 2-element operators. The 2-element operator receives two counts, and outputs the calculation results. The output result contains two counts.

The following is an algorithm used to construct all possible expressions:

(1) Add four Integers to the array.

(2) Take the arrangement of two numbers in the array and share the arrangement of P (4, 2. For each arrangement,

(2.1) +-*/each operator,

(2.1.1) Calculate the result based on the two numbers and operators listed here

(2.1.2) change the table array: remove the two numbers in this arrangement from the array and put the result calculated by 2.1.1 into the array.

(2.1.3) Repeat Step 2 on the new array

(2.1.4) restore an array: Add two numbers in the array and remove the result calculated by 2.1.1 from the array.

This is a recursive process. Step 2 is a recursive function. When there is only one number left in the array, this is the final result of the expression, and Recursion ends.

In the program, you must pay attention to recursive on-site protection and recovery, that is, before and after recursive calls, the on-site status should be consistent. In the above algorithm, the recursive field is the exponential group, 2.1.2 changes the array for the next layer of recursive call, and 2.1.3 restores the array to ensure that the current recursive call gets the next correct arrangement.

Parentheses () only change the operator priority, that is, the order in which operators are calculated. Therefore, parentheses are not required in the preceding algorithms. Brackets must be considered only for output.

3. process-oriented C implementation

This is the code of starfish, the former moderator of the csdn algorithm Forum. The program is concise and exquisite:

# Include
# Include
# Include
Using namespace STD;
Const Double Precision = 1e-6;
Const int count_of_number = 4;
Const int number_to_be_cal = 24;
Double number [count_of_number];
String expression [count_of_number];
Bool search (int n)
{
If (n = 1 ){
If (FABS (number [0]-number_to_be_cal) <precision ){
Cout <expression [0] <Endl;
Return true;
} Else {
Return false;
}
}
For (INT I = 0; I <n; I ++ ){
For (Int J = I + 1; j <n; j ++ ){
Double A, B;
String expa, expb;
A = number [I];
B = number [J];
Number [J] = number [n-1];
Expa = expression [I];
Expb = expression [J];
Expression [J] = expression [n-1];
Expression [I] = '(' + expa + '+ expb + ')';
Number [I] = A + B;
If (search (n-1) return true;
            
Expression [I] = '(' + expa + '-' + expb + ')';
Number [I] = A-B;
If (search (n-1) return true;
            
Expression [I] = '(' + expb + '-' + expa + ')';
Number [I] = B-;
If (search (n-1) return true;
                        
Expression [I] = '(' + expa + '*' + expb + ')';
Number [I] = A * B;
If (search (n-1) return true;
If (B! = 0 ){
Expression [I] = '(' + expa + '/' + expb + ')';
Number [I] = A/B;
If (search (n-1) return true;
}
If (! = 0 ){
Expression [I] = '(' + expb + '/' + expa + ')';
Number [I] = B/;
If (search (n-1) return true;
}
Number [I] =;
Number [J] = B;
Expression [I] = expa;
Expression [J] = expb;
}
}
Return false;
}
Void main ()
{
For (INT I = 0; I <count_of_number; I ++ ){
Char buffer [20];
Int X;
Cin> X;
Number [I] = X;
ITOA (x, buffer, 10 );
Expression [I] = buffer;
}
If (search (count_of_number )){
Cout <"success." <Endl;
} Else {
Cout <"fail." <Endl;
}
}

Compile with any c ++ compiler.

The algorithm of this program is basically the same as that described in 2. Basic principles. Bool search (int n) is a recursive function, and double number [] is an array. What is more important in a program is as follows:

(1) string expression [] stores the expressions generated in each step and is used in the final output. Expression [] is similar to number [] and is also the scene of recursive call. It must be changed before the next layer of recursive call and restored after the next layer of recursive call.

(2) number [] the array length is only 4. In search (), after two numbers are retrieved each time, the local variables A and B are used to save the two numbers. At the same time, the calculation results are added to the array, and adjust the array so that valid numbers are arranged in front of the array. After the next layer of recursive calling, use the local variables A and B to restore the entire array. The processing of expression [] is similar to that of number.

(3) because + * satisfies the exchange rate and-/does not meet the requirements, the program generates two numbers from the array,

For (INT I = 0; I <n; I ++ ){

For (Int J = I + 1; j <n; j ++ ){

The inner loop J is from I + 1-> N, not from 0-> N, because the order of the two numbers does not matter for the exchange rate. Of course, a special processing is performed on-/inside the loop, and four cases of a-B-a A/B/A are calculated.

(4) This program only finds the first solution. When the first solution is obtained, return true through multiple layers and output the result. Then the program ends.

(5) use double to solve the problem and define the precision to determine whether it is 24. Consider (5-1/5) * 5. The reason for doing so is known.

(6) brackets are added to each expression during output.

24-point classic algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.