[Beauty of programming] 4.8 count the time when all ants go out

Source: Internet
Author: User

In the ant climbing algorithm, only the time for the ant to exit is obtained, but the time for each ant to exit is not obtained. There is no fixed algorithm here. The Code is as follows:

# Include <iostream> Using STD: cout; Using STD: Endl; Using STD: swap; int left [29]; int right [29]; void fun () // first, determine whether the two ants are in the same position. If the two ants are in the same position, switch the direction of the two ants {for (INT I = 1; I! = 29; ++ I) if (left [I] & right [I]) Swap (left [I], right [I]);} void F () // determine whether to pass by. After passing by, exchange the order between the two ants {for (INT I = 1; I! = 29; ++ I) if (left [I] & right [I + 1]) {// swap (left [I], right [I]); // The comments are incorrect. // swap (left [I + 1], right [I + 1]); // swap (left [I], right [I + 1]); // correct switching method} void move () {for (INT I = 1; I! = 29; ++ I) {left [I-1] = left [I]; right [29-I] = right [29-1-I];} int main () {right [3] = 1; right [11] = 2; left [7] = 3; left [17] = 4; left [23] = 5; // right [5] = 1; // left [6] = 2; int COUNT = 0; For (INT I = 1; count! = 5; ++ I) {fun (); move (); F (); If (left [0] & ++ count) cout <left [0] <"No. Ant crawls out of \ n in the second" <I <"; if (right [28] & ++ count) cout <right [28] <"No. Ant crawls out of \ n" in seconds <I <";} return 0 ;}

The Code uses a simulation method to count the time when each ant goes out. If you only calculate the time when it goes out without considering which ant is, you can use the method in the book "The beauty of programming.

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.