"The beauty of Programming" reading notes (i): The problem of Chinese chess generals

Source: Internet
Author: User


Long-awaited started out, in the jump ticket for one months, even though there are many mistakes in the book has not changed to (with a full page of errata), but the feeling can not wait for the next version. Hurry to the bookstore to buy back, eat dinner lying in bed comfortable to see. After roughly looking, the overall feeling is that the content of the book is not "out of the masses", many of us usually live, work often encounter. The topic is not difficult, basically give an introduction to the algorithm and enough time, most people can solve the problem. But note the subtitle--"Microsoft Technical Interview Experience", this sets a tone for this book: In the face of these problems that we are not unfamiliar with, and not particularly difficult, in the limited time, (possibly) more tense mood, how to fully develop their own analysis and problem solving ability, How to solve the problem correctly and beautifully is the key. I think, in peacetime study time perhaps our left hand "the algorithm introduction", right hand "the beauty of programming" the effect will be better.

The problem of Chinese chess generals is simpler, so we don't have to ask for an introduction to algorithms for the time being. The specific description of the problem is: (according to the basic principles of Chinese chess) on the generals chessboard with only two, find out where all the two sides can be drop (generals cannot meet), but only one variable can be used. Intuitively, we think, as long as we traverse generals all possible locations, remove the generals conflict position. As you can see, the rest of the problem is how to use a variable to do the traversal of the double loop. The method given in the book is to split a byte variable into two uses, the first half represents the "handsome" can go to the position, the latter variable represents the "will" can go to the position (has already "will" and "handsome" can go 3*3 the position of the number), the use of bit operation can get two counters function. The solution in the book three uses the structure body to solve one variable to traverse the double cycle the question, the thought in the same way. What's really interesting is the solution two, which has the following code:

int var = 81;
while (var--)
{
if (var/9% 3 = var% 9 3)//conflict occurs
Continue
Else
printf (/** print feasible position **/);
}

When I see this solution, I have some feeling in my heart. In the last few months, I have not msra the interview failed to annoy. But after seeing this solution, I think I really have to work harder. Just a few lines, embodies the beauty of simplicity, only look at this is worth the money (joking). Although some bulls may say it's no big deal, I think it would be a great achievement if I could write this code when I was interviewing for this question. Most of the time we do not need to know how the Yi of the time complexity of the hill sort is calculated, nor does it need to prove that an optimization problem satisfies the "quasi-matrix" condition, and that we just have to do it beautifully on such a "simple" question.

Go back and analyze the solution. "Will" and "handsome" in their own 3*3 inside the lattice of walking around, we need to verify 9*9=81 kind of position relationship, this is the origin of i=81. In addition, we must understand the meaning of I/9 and i%9. As we know, integer I can be composed of part two, namely var= (VAR/9) *9+var%9, which var<n. We note that, in the process of changing from 81 to 0, the var%9 change is equivalent to the inner loop, and the VAR/9 is relative to the inner loop. In this way, the author uses a variable i to obtain the value of two variables at the same time.

Simple is the United States, relative to the solution of a large section of code, I would prefer me to write the solution in the next interview two.

In fact, this problem can also be extended, that is, how to use a variable to achieve the triple loop effect. In other words, if given the following loop:

int counter = 0;
for (int i = 0; i < 5; i++)
for (int j = 0; J < 4, j + +)
for (int k = 0; k < 3; k++)
{
System.out.println ("counter=", "+counter+", i= "+i+", j= "+j+", k= "+k");
counter++;
}
The results are as follows:
Counter=0, I=0, j=0, k=0
Counter=1, I=0, j=0, k=1
counter=2, I=0, j=0, k=2
Counter=3, I=0, J=1, k=0
Counter=4, I=0, J=1, k=1
.... Middle slightly
counter=59, i=4, j=3, k=2

The question is (1) How do we print out the same results? (2) What if it's N-cycle?

In the face of the first question, in fact, the original Chinese chess generals an extension of the problem, that is, add a "king" on the board, its walking rules and generals the same. So the chessboard became the Three Kingdoms hegemony:-), generals Wang can move around the number of lattice is 3, 4, 5, their mutual exclusion conditions can be set according to need.

At this point, you need to traverse a triple loop with just one variable. The intuitive approach is to take a 4-byte int apart as a method. I'm only looking at method two here.

With only one variable to solve the expansion of Chinese chess generals problem, our code should be as follows:
int var = 3*4*5;
while (var--)
{
if (/** conflict condition **/)//conflict occurs
Continue
Else
printf (/** print feasible position **/);
}

In a conflict condition, we need to know what the i,j,k is when Var gets a particular value (that is, the first var+1 cycle) (so we can determine if the generals position is conflicting)

From the results of the example above, we can see that the value of the counter (that is, the current number of loops) and the ternary group (I,J,K) is one by one corresponding, the more The outer loop changes more slowly, they meet what relationship?

K's value is best determined, we all know is var%3.
In the original generals problem we know that the value of J should be VAR/3, but since J has a layer of loops, it needs to be adjusted to become var/3%4
The value of the outermost loop i is (var/(3*4))%5.

That is: k=var%3//There is no cycle under the
J=VAR/3//below has several loops with a cycle length of 3
i=var/(3*4). There are several loops with a 3*4 length below it.

So we can easily draw a 4-cycle formula:
for (int i = 0; i < 5; i++)
for (int j = 0; J < 4, j + +)
for (int k = 0; k < 3; k++)
for (int p = 0; p < 3; p++)

p=var%2//No loops under it
K=VAR/2//below has several loops with a cycle length of 2
j=var/(2*3))//under which there are several loops with a cycle length of 2*3
i=var/(2*3*4)//under which there are several cyclic lengths 2*3*4 loops

Here is a variable to achieve triple loop


int var = 2*3*4*5;
while (var--> 0) ... {
System.out.println ("var=" +var+ ", i=" + (var/(2*3*4))%5) +
", j =" + ((var/(2*3))%4 + ",
K= "+ ((VAR/2)%3) +",
P= "+var%2);
}



The result:
var=119, i=4, j=3, k=2, p=1
var=118, i=4, j=3, k=2, p =
var=117, i=4, j=3, K=1, p=1
... Middle slightly
Var=5, I=0, j=0, k=2, p=1
Var=4, I=0, j=0, k=2, p =
Var=3, I=0, j=0, K=1, p=1
var=2, I=0, j=0, k=1, p =
Var=1, I=0, j=0, k=0, p=1
Var=0, I=0, j=0, k=0, p =

The principle of N heavy circulation is the same, no longer repeat.

PS: See the final example of the result is not with the "Introduction to the algorithm" in the analysis of the second chapter of the binary counter very much like? It's just different here.:-)

[Errata: Line seventh of P19 code listing 1-7, should be changed to if (i.a%3!= i.b%3)]

I would like to share this article with you 2008/04/05

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.