Generating a random array

Source: Internet
Author: User
Tags shuffle

Not much to say, directly on the code test, before the online to see a generated random array, write really not how, the following is my way, there is a better way to communicate

C Code: Soon and quickly

#include <stdio.h> #include <stdlib.h> #include <time.h>void main () {        long last = 1000000;        Long *arr= (Long) malloc (last*sizeof (long));        Long *brr= (Long) malloc (last*sizeof (long));        Long I,r;        Srand ((unsigned) time (NULL));        for (i=0;i<last;i++) {                arr[i]=i;        }        while (last>0) {                r=rand () *rand ()%1000000;                if (arr[r]==-10) continue;                BRR[1000000-LAST]=ARR[R];                arr[r]=-10;                last--;        }        printf ("%d\n", Brr[0]);        printf ("%d\n", last);}

PHP Code: The own function, in fact, is the implementation of the C shuffle 22 random switching principle (fast sorting is also two exchanges, so the space complexity must be a little lower)

<?php$arr = Range (0, 1000000), $length = 1000001;shuffle ($arr), echo $arr [2];echo "\ n"; echo Xdebug_time_index ();//end

PHP Code: The implementation of their own, not the general slow to 17s or so, is already very fast one way, the other way will generally show that the memory is exhausted

<?php$arr = Range (0, 1000000), $length = 1000001, $out = Array (), while ($length) {        $R = Mt_rand (0, $length);        $out [] = $arr [$R];        $arr [$R]= $arr [$length-1];        $length--;} Shuffle ($arr); Echo $arr [2];echo "\ n"; echo Xdebug_time_index ();//end

Generating a random array

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.