[Cocos2dx] shuffles algorithm created by landlords

Source: Internet
Author: User

As a landlord project, the shuffling algorithm is a very important step. It is very well-studied for how to "wash" evenly and "wash" randomly, the advantages and disadvantages of algorithms directly affect the performance. Here I will give an algorithm to sort the 54 numbers 0-53 directly, which is quite random after testing. Thank you for your guidance! This algorithm is used by the server to return cards to the client. The main idea is to constantly change the cards and switch the positions of the two cards. If the number of cycles increases, the randomness will be stronger, shuffling works better!

Code:

C #:

Using System; using System. collections. generic; using System. linq; using System. text; random sorting of namespace {class Program {static void Main (string [] args) {int [] data = new int [54]; for (int I = 0; I <54; I ++) {data [I] = I;} Console. writeLine ("Before sorting:"); foreach (int I in data) {Console. write (I + ",");} long tick = DateTime. now. ticks; Random random = new Random (int) (tick & 0 xffffffffL) | (int) (tick> 32 )); // card exchange algorithm for (int I = 0; I <54; I ++) {int t1 = random. next (0, 54); int t2 = random. next (0, 54); int temp = data [t1]; int data1 = data [t1]; int data2 = data [t2]; data [t1] = data2; data [t2] = temp;} Console. writeLine ("sorted:"); foreach (int I in data) {Console. write (I + ",");}}}}
Run:




C ++:

Void HelloWorld: xipai () {for (int I = 0; I <54; I ++) {data [I] = I ;} // random number // shuffling for (int I = 0; I <54; I ++) {int t1 = arc4random () % 54; int t2 = arc4random () % 54; int temp = data [t1]; int data1 = data [t1]; int data2 = data [t2]; data [t1] = data2; data [t2] = temp ;} printf ("shuffled: \ n"); for (int I = 0; I <54; I ++) {printf ("% d ", data [I]) ;}}

Result:


We will find that it is quite random. If we take the for loop bigger, it will be more random!

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.