String inversion, a magic algorithm-read programming Pearl (second edition)

Source: Internet
Author: User

Recently, I have been slowly reading the English name Programming Pearls of "second edition of Programming Pearl River". The book is very thin and contains more than 160 pages ), but as shown in its cover "the works that have been consistently admired by many masters over the past 20 years", how can I read this classic one at once? There are many simple but interesting examples in the book, and the author's practical experience and points of attention are worth reading a little bit. If it is not enough, I will try again in the second or third time...

In addition, a few days ago, we found that BKJIA's reading channel included online reading of the entire book "Programming Pearl" (English name: More Programming Pearls!


Return to the topic. Chapter 2 "Aha! In the algorithm, the author gives three "small questions". The second one is to rotate the x position of a one-dimensional vector with n elements to the left. For example, if ABC123DEF456 is rotated three places to the left, 123DEF456ABC is obtained. The requirement is that the operation is completed in proportion to n.

The question is small, but as the title of this chapter is "Aha! As shown in the algorithm, the author wants to emphasize the clever and powerful algorithms. Among them, there are three solutions to this question.

*.Use temporary Array

This is probably a solution that most people will think of. We will copy the first I of the given vector x to a temporary array, move the remaining n-I elements to the left and then copy the I elements in the temporary array back to the position behind x.

Code implementation:

  1. Public void tempArrReverse (char [] arr, int len, int m ){
  2. Char [] temp = new char [m];
  3. // Save the first m elements of the array to the temporary Array
  4. For (int I = 0; I <m; I ++ ){
  5. Temp [I] = arr [I];
  6. }
  7. // Forward the len-m elements behind the Array
  8. For (int I = m; I <len; I ++ ){
  9. Arr [I-m] = arr [I];
  10. }
  11. // Copy all elements of the temporary array to the original array
  12. For (int I = 0; I <m; I ++ ){
  13. Arr [len-m + I] = temp [I];
  14. }
  15. }


Obviously, although the above solution is simple and mobile, it uses I extra space, which is a waste of space. As a result, another author praised the solution "clever acrobatics.

*."Clever acrobatics"

First, move x [0] to the temporary variable t, then move x [I] to the position where x [0] is vacated, and x [2i] to x [I, by analogy, the subscript in x [] is used to modulo the length n of x [] until the element is extracted from x [0, in this case, you should place the temporary variable t in the previous position and start the next iteration, that is, perform similar operations on x [1.

The intuitive figure in the book is as follows:

650) this. width = 650; "border =" 0 "alt =" "src =" "/>

Code implementation:

  1. Public void juggleReverse (char [] arr, int len, int m ){
  2. Int k = 0;
  3. For (int I = 0; I <m; I ++ ){
  4. K = 1; // each iteration starts from 1 x shift.
  5. Char temp = arr [I];
  6. While (k * m + I) % len! = I ){
  7. Arr [(k-1) * m + I] = arr [k * m + I];
  8. K ++;
  9. }
  10. Arr [(k-1) * m + I] = temp;
  11. }
  12. }

However, as the author reminds me, please be careful when converting this idea into code !" In fact, my implementation is only feasible when the length of the original vector n is an integer multiple of the displacement I, And I = 3 is also used in the book, n = 12 This example demonstrates how to explain it, and I feel that the translation here is a bit awkward and cannot be understood smoothly. I have to find out what the original article says.

If you draw a picture on the paper that is not an integer multiple, you will find that the actual situation is much more complicated. Some elements may be placed behind the correct position, and I don't want to use a lot of if... else statements to determine the situation, because I think I did not understand the author's ideas, so I have to think about it for the time being.) I hope you can give me some advice. =)

*.Another clever way of thinking-Power of primitives

In fact, the question refers to the string reverse. I do not know if "rotation" in the original article is the word. I have to verify it ), this section in the book "The Power of primitives" mentions that "some programming languages provide rotation as primitive operations for vectors ". If you already have function primitive operations that reverse some elements specified in the array), the next solution will be more interesting.

The original problem can be seen as follows: to regard the original array as AB, we need to convert it to ba. First, we need to reverse the pair array a separately to obtain the result of a 'ba' representing the result after a is reversed ), similarly, if B is reversed separately, a 'B' is obtained, and then the obtained a' B 'is reversed together to obtain a' B') '. This is the final result ba, do not believe you try it on paper or take a look at the more interesting and operable examples below ).

Code implementation:

  1. // Primitive operation-reverse Array
  2. Public void reverse (char [] arr, int start, int end ){
  3. Int mid = (start + end)/2;
  4. For (int s = start, I = 1; I <mid; s ++, I ++ ){
  5. Char temp = arr [s];
  6. Arr [s] = arr [end-I];
  7. Arr [end-I] = temp;
  8. }
  9. }
  10. Public void useReverse (char [] arr, int len, int m ){
  11. Reverse (arr, 0, m );
  12. Reverse (arr, m, len );
  13. Reverse (arr, 0, len );
  14. }


In fact, here I think the author has made me feel clever about the algorithm. Different understandings and opinions on the same problem can inspire such a brilliant solution. But in fact, you will also find that this classic book frequently lists historical information such as the solutions and application of other masters to a certain problem. For example, the book mentions that Ken Thompson also uses this code in its editor and transpose code, and "claims that even at that time, it can be compiled into a mythical story ". Isn't it amazing? See the following.

*.Feasible proof methods-Hand shake

If you want to rotate an array with 10 elements and we only have 10 fingers) Up to 5 positions, let the palms of the two hands align with yourself, in fact, the two hands on the right hand actually agree to the plane), see:

650) this. width = 650; "border =" 0 "alt =" "src =" "/>


In fact, if you read this book yourself, you will find more wonderful! Isn't such a book worth reading a little bit?


This article is from the "ant" blog, please be sure to keep this source

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: 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.