Randomly retrieve several different numbers from an array

Source: Internet
Author: User

Randomly retrieve several different numbers from an array

/** This program is to randomly retrieve several different elements from an array that is not repeated * The difficulty is to prevent the number of elements that have been obtained (especially when the last element is obtained ). ), try to reduce the collision as much as possible * // first algorithm, the idea of others on CSDN/* $ num = 0; $ array = array (1, 2, 3, 4, 5, 6, 7, 8, 9); $ arr = array (); $ g = 5; $ tag = true; while ($ tag) {$ count = count ($ array); $ t = rand (0, 1); if ($ t = 1) {$ arr [] = $ array [$ num]; unset ($ array [$ num]);} $ num ++; if (count ($ arr) ==$ g) {$ tag = false;} if ($ num = $ count) {$ num = 0; // loop} var_dump ($ Rr); * // The second algorithm. // You can replace the data with the unobtained data after each fetch, and then randomly obtain the value of function swap (& $ a, & $ B) from the unobtained data) {$ temp = $ B; $ B = $ a; $ a = $ temp;} $ result = array (); $ src = array (); for ($ I = 0; $ I <40; $ I ++) {$ src [] = $ I + 1;} $ arr_len = count ($ src ); $ count = 20; $ index = 0; while ($ index <$ count) {$ random = rand (0, $ arr_len-$ index-1 ); $ result [] = $ src [$ random]; swap ($ src [$ random], $ src [$ arr_len-$ index-1]); $ index + = 1;} print_r (json_encode ($ result); print_r (json_encode ($ src ));





 

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.