24-point program: process-oriented and object-oriented C ++

Source: Internet
Author: User
Count the 24-point program: process-oriented and object-oriented C ++-general Linux technology-Linux programming and kernel information. The following is a detailed description. 1. Overview

Given four integers, each digit can only be used once. Any +-*/() is used to construct an expression, and the final result is 24, this is a common 24-point game. There are a lot of programs in this area, and they are generally used to solve the problem. This article introduces a typical 24-point algorithm, and provides two specific 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 binary operator receives two parameters and outputs the calculation result. The output result is used for subsequent calculation.

As described above, the algorithm for constructing all possible expressions is as follows:

(1) Add four Integers to the array.
(2) sort two numbers in the array, with a total 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 for the new array.
(2.1.4) restore an array: add the 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 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 very 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 ;
B = number [j];
Number [j] = number [n-1];

Expa = expression;
Expb = expression [j];
Expression [j] = expression [n-1];

Expression= '(' + Expa + '+ expb + ')';
Number= A + B;
If (Search (n-1) return true;

Expression= '(' + Expa + '-' + expb + ')';
Number= A-B;
If (Search (n-1) return true;

Expression= '(' + Expb + '-' + expa + ')';
Number= B-;
If (Search (n-1) return true;


Expression= '(' + Expa + '*' + expb + ')';
Number= A * B;
If (Search (n-1) return true;

If (B! = 0 ){
Expression= '(' + Expa + '/' + expb + ')';
Number= A/B;
If (Search (n-1) return true;
}
If (! = 0 ){
Expression= '(' + Expb + '/' + expa + ')';
Number= B/;
If (Search (n-1) return true;
}

Number=;
Number [j] = B;
Expression= 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= X;
Itoa (x, buffer, 10 );
Expression= 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. The important points in the program are explained 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 obtaining two numbers each time, use the local variables a and B to save the two numbers and add the calculation results 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/B/a are calculated.

(4) This program only obtains 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 for each expression during output.

4. Object-Oriented java implementation

The algorithm is still the same as 2. Basic principles. The advantage of using objects is that the program structure is clearer and the function expansion is more convenient. Of course, the efficiency will be lower than that of structured programs. The object design is as follows:

Description of methods contained in variable classes
Numberdouble valueString toString () to clearly express the recursive definition of expression
Expression extends NumberNumber left
Number right
Char operatorString toString ()
CalculatorNumber [] numbers
Expression [] expressionsadd () clear () // operate numbers
Calculate ()
Permutor permutor () Main class of the java program, implementing algorithms
Permutorint I, jboolean next () arrangement generator, similar to iterator, generates the arrangement of two elements from a specified array

Complete source code please see http://www.ch2000.com.cn /~ Ganxc/expression.zip. This is a simple 24-point computing program and expression parsing and evaluation program. For more information, see ReadMe.txt.

We can see many benefits of object-oriented design:

(1) when outputting an Expression, you only need to rewrite Number. toString () and Expression. toString. To output necessary parentheses and remove unnecessary parentheses, you only need to rewrite Expression. toString.

(2) The Permutor arrangement generator greatly simplifies the process structure.

(3) good encapsulation. generate three numbers of arrays. Theoretically, you only need to modify the internal implementation code of Permutor.

(4) good reusability. Numbers and expressions can be reused in other places, such as Expression parsing programs.

Of course, this is just an exemplary code, and there are many internal aspects that can be encapsulated and simplified. It is very convenient to modify the framework of the class.
Related Article

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.