Thread: A simple question about selecting elements in an array

  1. #1
    Unregistered
    Guest

    A simple question about selecting elements in an array

    How do you select MULTIPLE elements in an array randomly?

    I'm trying to select 10 different elements in an array at once in a loop. The loop will be repeated over and over again, but the value of the 10 elements will be saved on to a global variable. Any suggestions, ideas are welcome. Help please....

    Linus

    [email protected]

  2. #2
    unregistered
    Guest

    Lightbulb

    //zMan -- Perhaps one way to do this will help you

    int g_myArray[10] = {0};


    void LoadGlobalArray(int someArray[], int nLastIndex);

    void main(void)
    {
    int myArray[100] = {100,200,300,213,12,......,};

    LoadGlobalArray(myArray, 100 );

    ....

    }

    /*
    The way this function works it grabs values from the entire
    array and places them in the first ten entries. You can think of
    it as a shuffle--except that the entire array is not out of order but
    the first ten positions are.
    It modifies the original array because it shuffles the values.
    If you preferred not to modify the original array you can store the
    values in another array of 10 elements. Checking for duplicates
    would have to be accomplished by looping through the array of 10
    prior to adding a new item to item to it.


    */
    void LoadGlobalArray(int someArray[], int nLastIndex)
    {
    int nRandom, nTemp;

    //Shuffle the first ten positions in the array
    //We could shuffle the whole array but what is
    // the purpose when we only need ten values?
    for(int i = 0; i < 10; i++)
    {
    nRandom = rand() % nLastIndex;
    nTemp = someArray[i];
    someArray[i] = someArray[nRandom];
    someArray[nRandom] = nTemp;
    }

    //do not..do not try to accomplish the assignment
    //task in the loop above.... You may get duplicate values
    for(i = 0; i < 10; i++)
    {
    g_myGlobalArray[i] = someArray[i];
    }
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sum all odd array elements?
    By Marth_01 in forum C Programming
    Replies: 9
    Last Post: 11-04-2008, 10:47 PM
  2. simple array question
    By agentsmith in forum C Programming
    Replies: 1
    Last Post: 05-05-2008, 10:00 AM
  3. simple char array question
    By yahn in forum C++ Programming
    Replies: 4
    Last Post: 02-08-2006, 09:18 PM
  4. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM
  5. simple array question
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 02-16-2002, 10:43 PM