Java programming capability enhancement (2)-General Solution to search solutions

Source: Internet
Author: User

A few days ago, I published an article titled Java programming capability enhancement-wolf and goat crossing the river. Some friends pointed out some problems,

These problems are: 1. I didn't adopt the object-oriented idea and didn't define my own classes. It seems that I have nothing to do with Java, like C programming thinking. 2. No code ideas are provided. 3. Doubt whether Java programming capability can be improved. This article first explains the first problem, then provides a general solution to this type of problem, and then analyzes the previous Code of the wolf and goat crossing the river, it mainly analyzes the Java knowledge involved.


--------------------------------------------------------------------------------

First, programming is to solve the problem, and solving the problem is the final principle.

Simply put, the program processes user input and then outputs the processing result. The human needs are expressed in the form that the computer can understand, then processed by the computer, and then the computing results are converted into the form that the user can understand. Information Representation is a problem of database structure, and information processing is a problem to be solved by algorithms. Therefore, data structure and algorithms are very important in computer courses. The implementation of data structures and algorithms requires a language, so you may see the data structure (C language) or data structure (Java language). The algorithm usually uses pseudo code.

If an object-oriented analysis is used for the wolf-goat cross-river problem, you need to consider the objects that appear in the description, and abstract the classes and class levels according to these objects, the objects involved here include three wolves, three sheep, one ship, the rule of coexistence of Wolf and sheep, and the capacity of the ship. However, these objects basically have no attributes or behaviors, therefore, it is not appropriate to construct a class, and the object-oriented design is not carried out in the reference code given.

In addition, this topic mainly focuses on how to solve the problem, concerning the number of sheep and wolves, and how to transport wolves and sheep to the other side of the river under various constraints, therefore, algorithms are the focus of the answers.

Java language features such as String, StringBuffer, Integer, exception handling, array, and method recursive calling are used in the algorithm implementation process. Therefore, it cannot be said that it is irrelevant to Java.

I personally think there are three things to be mastered in Java: basic syntax, common class libraries, and object-oriented features. This exercise mainly strengthens the first two aspects.


--------------------------------------------------------------------------------

Second, search for solutions

This type of problem has the following features:

1. There is an initial state. For example, three wolves and three lambs need to cross the river. This means that the first three wolves and three lambs are on the bank of the river.

2. There is a target State. For example, three wolves and three lambs must arrive at the opposite side of the river. This means that the last three wolves and three lambs must be on the opposite side of the river.

3. Some rules can be used to change the status. For example, two wolves can be shipped to the opposite side of the same ship, at this time, the state is that there are 3 sheep and 1 wolf on one side of the river, and there are 2 waves on the other side of the river (of course, you can calculate the number on the other side according to the number on one side, because it is either here or there ).

How do people solve such problems? See the following figure:

First, consider three wolves and three sheep on the left. The ship can hold two animals, so there are five solutions. Then, let's see if the results produced by each solution are the expected results. If not, the figure above shows the process. In the figure, the right indicates that the animal is transported to the other side, and the left indicates that the ship is returned.

How does the program implement this process?

The implementation process of the program is a simulation of human thinking. There are two ways. One way is to find them by layer. In the initial state, five possibilities are considered, and then five possibilities are analyzed, then, consider the possible changes in each situation until the target State is found or the status cannot be changed. This is called breadth-first search. Another method is to consider one of the five cases first. After consideration, consider the status that can be transferred in this case, and then consider one of them, which is called Deep priority search. The previous reference answer uses deep-priority search.

For example, if priority is given to breadth: The processing order of each State is: 1 (first layer) 2 3 (second layer) 4 5 6 (third layer) 7 8 9 10 (Layer 4)

If priority is given to depth: the processing order of each State is: 1 2 4 7 3 5 8 9 6 10, 2 after the situation is processed and then 3 after the situation is processed, in the same 5 cases, the lower 6 cases will be processed after the processing is complete.

The key parts of the algorithm are as follows:

1. Define a structure to indicate the status, including the initial status, intermediate status, and target status. In my reference code, int state [] is used to indicate the status.

2. Specify the initial and target statuses. In the code, the initial status is [3, 3], indicating three wolves and three lambs on the shore. The target status is [0, 0], indicating that both the wolf and the goat have crossed the river.

3. Specify the state conversion rules. Generally, each rule can be defined as a method. The input of a method is a state, and the output is another state. In the code, the move method completes this function, but I write multiple rules in the same method.

4. Write the main program, starting from the initial state, and continuously converting the State until the end. There are two Processing Methods: recursive call of methods, and loop.

Possible problems:

1. Endless loops. The most intuitive example is to let a wolf go to the other side, and then return, and then come back ..., there will never be an end, so you need to control the problem. The effective way is to record the status that has elapsed. If the problem is found to be repeated, give up the solution. There are two areas in the program for control.

2. the space for solution may be very large. If you do not take any measures, it may never end up running. For example, when playing chess, everyone knows who wants to go far, and who can win, if the computer considers the situation after step 1, it may be hard to win, however, it takes too much computing for the computer to consider Step 1. If there are 20 steps in each step, consider the power of 100 to the power of 20. You can imagine how big this number is. Heuristic Search and pruning are usually used for this problem. For more information, see related books.


--------------------------------------------------------------------------------

Iii. key code analysis

For the complete code, see html "target = _ blank> Java Programming capability enhancement-wolf sheep crossing the river

Key Point Analysis:

1. public void next (int state [], StringBuffer str)

Recursively calls a method to process all States under a specified state.

2. if (str = null) {// indicates the first step
// A wolf and a sheep
NewState = move (state, "-1-1 ");
Next (newState, new StringBuffer ("-1-1 "));
// The two wolves cross the river
NewState = move (state, "-2-0 ");
Next (newState, new StringBuffer ("-2-0 "));
Return;
}
You can also process the initial status in the following code. If the code is merged, You need to determine whether the str is empty. In addition, the return here cannot be omitted.

3. if (state [0] = 0 & state [1] = 0) {// All are transferred to the right bank.
PrintResult (str );
Return;
}
Indicates that the target status is obtained and the processing is complete.

4. // two wolves
If (state [0]> = 2 &&! Str. substring (0, 4). equals ("+ 2 + 0 ")){
NewState = move (state, "-2-0 ");
If (check (newState )){
Next (newState, new StringBuffer (str). insert (0, "-2-0 "));
}
}
Note: new StringBuffer (str). insert (0, "-2-0") cannot be written as str. insert (0, "-2-0 ")

In addition! Str. substring (). equals ("+ 2 + 0") prevents animals from going back to the ship.

5. public int [] move (int state [], String info ){
Int lang = 0;
Try {
Lang = Integer. parseInt (info. substring (0, 2 ));
} Catch (Exception e ){
Lang = Integer. parseInt (info. substring (1, 2 ));
}
Int yang = 0;
Try {
Yang = Integer. parseInt (info. substring (2 ));
} Catch (Exception e ){
Yang = Integer. parseInt (info. substring (3 ));
}
Int [] result = new int [state. length];
Result [0] = state [0] + lang;
Result [1] = state [1] + yang;
Return result;
}

Note: The use of try statements is abnormal when + 3 is converted to a number.

In addition, you cannot directly modify the state element value and then return the state.

6. public boolean check (int state []) {
The number of sheep cannot be less than the number of wolves.

7. public boolean hasExist (StringBuffer str ){
Determine whether an infinite loop exists.

8. public void printResult (StringBuffer str ){
Output result scheme.

You can try to use the breadth-first method to implement code, instead of recursion (if there are many layers of recursion, there will be a stack overflow problem ).

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.