Interview question: produce an array of length 100, each item in the array randomly fills the number between 1-100 and guarantees no repetition

Source: Internet
Author: User
Tags repetition

Turn from: http://blog.csdn.net/yanghua_kobe/article/details/6253227


This is an interview question:

Refer to 3 ways on the Web, C # implementation:

Method One:

[C-sharp]  View plain copy print? #region   Method One                // Storage 1-100                int[] num  = new int[100];                //indexNum[0]=1;...indexNum[99]=100; (not repeat)                 for  (Int i = 0; i < num. length; i++)                {                    num[i]  = i + 1;                }               Random r  = new rAndom ();               //storage Final Results                 int[] result =  new int[100];               int  max = 100;//set the maximum value of random number                 for  (Int j = 0; j < result. length; j++)                {                    // Computes the randomly generated array index (0-99)   NOTE: The upper bound value:100  cannot be taken to                     int index = r.next (0, max);                    //Check out the number of the index stored in the location                     result[j] = num[index];       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//replaces the number that has been put into result with the last number                     // In this way, the numbers from 0 to max-1 in the NUM array are not stored in result and are not duplicated                     num[index] = num[max - 1];                    //randomly generated array index Max minus one                     max--;                }                //Print Results                 for  (int i = 0; i < 100; i++)                 {                    if  (i % 10 == 0)                    {                         console.writeline ("/r/n");                    }                    console.write (result[i] +  " ");               }                console.read ();                 #endregion       


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.