mode of an array

This is a discussion on mode of an array within the C Programming forums, part of the General Programming Boards category; need program with an array of 100 elements that are generated randomly from numbers 1-30 I know this part. Then ...

  1. #1
    Need Help
    Guest

    Red face mode of an array

    need program with an array of 100 elements
    that are generated randomly from numbers 1-30
    I know this part.

    Then need second array to sort and find the numbers that come up the most times.
    How do you do this part???
    I assume a counter is part of it.
    But how do you count "like" elements and keep tract of each instance??

    eg. say my array is as follows (made it 10 elements to simplify):


    array_a[10]={1,30,24,26,1,2,24,1,1,1};
    now code to sort it is not a problem,
    but what would second array be doing to add the like numbers?
    1 comes up 5 times (1 is the mode of the random array set)
    24 comes up 2 times
    30, 26, and 2 each come up once

    must also be prepared for multiply modes of the random array set
    (my program will have 100 elements in random array, so it highly likely that a couple numbers may come up the same amount of times - the most times)

    Would the second array assign element of first array to a specific element location and then increment each time that happens?
    If so would there be 30 elements of array that is part of the sort and counting??

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    If so would there be 30 elements of array that is part of the sort and counting??
    Yeah you've answered your own question. If you had an array of 100 elements -

    short arr1[100];

    filled with 100 random numbers from 1-30 you would have a second array -

    short arr2[30]; //ensure all elements are initialised to zero

    then you would loop through the first array incrementing the second array when a value is found -

    for(int i=0;i<100;i++)
    {
    arr2[arr1[i]-1]++;
    }

    Then the second array contains the first array sorted and counted. If you want to print the first array in it's sorted state you can use a nested for loop to print out the second array -

    for(int j=0;j<30;j++)
    {
    for (int k=0; k<arr2[j] ;k++)
    cout << j+1 << endl;
    }

  3. #3
    Need Help
    Guest

    finding repeated element value

    Zen:

    I don't get the loop for arr2;

    arr1 would be 100 elements of random values
    arr2 would be 30 elements that would increment as value of each element of arr1[n-99] equals 1-30; so say arr1[0] = 30; then in arr2 I suspect to increment arr2[n-29] //30 elements means the subscript of elements is 0-29; and arr2[29] is position for number 30 to be incremented.

    -----------------------------------------
    you say to do the following:

    then you would loop through the first array incrementing the second array when a value is found -

    for(int i=0;i<100;i++)
    {
    arr2[arr1[i]-1]++; // how does affect the 30 elements of arr2 ???
    }
    -------------------------------------------------------------------
    Then the second array contains the first array sorted and counted. If you want to print the first array in it's sorted state you can use a nested for loop to print out the second array -

    // we are only printing out the mode of the array arr1[100]
    which is the number that comes up most often

    // in this case arr2 would have 30 elements but the values in arr2 elements are incrementing as the number of times the numbers 1-30 come up in the random listing of elements in arr1[100]; how do you increment the element in arr2 and have those correspond to the value of element of arr1 ??? then how do you choose the elements with the highest value - could be just one element with high incremented value, could be more than one. How does program work to pull each element to




    for(int j=0;j<30;j++)
    {
    for (int k=0; k<arr2[j] ;k++)
    cout << j+1 << endl; //how is this sorting and
    } // counting
    // and the last line doesn't
    // look like C function to me

  4. #4
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Sorry, I didn't read your post properly, my method would sort them by value rather than frequency. That last bit should have read -

    for(int j=0;j<30;j++)
    {
    for (int k=0; k<arr2[j] ;k++)
    printf("%d\n",j+1);
    }

    If you are using this method you would require another array that would act as an index for the frequency or a multi-dimensional array, with one part storing the number and the other part storing it's frequency. This array could then be sorted.

  5. #5
    Need Help
    Guest

    only 2 arrays are asked for

    Zen,

    I will have to study your suggestion a bit.
    But we were expressedly told to use only 2 arrays; one with the 100 elements randomly selected and one to sort and count the values...incrementing each element as often as it occurs and then sorting to get the number occurring most often.

    Some instructors kinda give hints. This one does not.

    Thanks anyways.

  6. #6
    Unregistered
    Guest
    array1 has the data you want to count
    array2 has the count of each number (ie: value)

    If you know the value of the data entered, use that value as an array index to keep track of the total number. For example, let's say I have only 3 possible "answers".
    Code:
    int arrayList[SIZE] = { a bunch of numbers here, let's say 0,1,2 }
    int answerCount[3];
    
       // Set all "answerCount" values to 0, and then start counting:
    
    for( x = 0; x < arrayListSize; x++ )
    {
       // arrayList[x] will have an answer in it, who's value will be
       // only 0, 1, or 2.
    
       // here, we're taking the value of "arrayList[x]"
       // and using it as the index for the second array
       // and incrementing that count
       answerCount[ arrayList[x] ]++;
    }
    Quzah.

  7. #7
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    If you can use a two-dimensional array as one of the arrays then this should work -

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    
    #define INDEX 0
    #define COUNT 1
    #define TOTAL_NUMBERS 100
    #define RANGE 30
    
    int main()
    {
        short arr1[TOTAL_NUMBERS]={0};
        short arr2[RANGE][2]={0};
        int i,j;
    
        //Seed random number generator
        srand((unsigned)time(NULL));
        
        //Enter random numbers
     for (i=0;i<TOTAL_NUMBERS;i++)
        {
            arr1[i]=rand()%RANGE+1;
        }
    
        //Initialise index 1->30
     for(i=0;i<RANGE;i++) 
        { 
            arr2[i][INDEX]=i+1; 
        } 
    
        //Count occurances and place next to index
     for(i=0;i<TOTAL_NUMBERS;i++) 
        { 
            arr2[arr1[i]-1][COUNT]++; 
        } 
    
        
        //Sort array max occurances first
     for( i = 0; i < RANGE-1; i++ )
            for( j = RANGE-1; j > i; j-- )
                if( arr2[j][1] > arr2[j-1][1] )
                {
                    short temp1=arr2[j-1][INDEX];
                    short temp2=arr2[j-1][COUNT];
                    arr2[j-1][INDEX]=arr2[j][INDEX];
                    arr2[j-1][COUNT]=arr2[j][COUNT] ;
                    arr2[j][INDEX] = temp1;
                    arr2[j][COUNT] = temp2;
                }
    
        //Print sorted array
     for( j=0;j<RANGE;j++) 
        { 
            printf("%2d : %2d\n",arr2[j][INDEX],arr2[j][COUNT]);
        } 
    
    
        return 0;
    }
    
    

  8. #8
    Need Help
    Guest

    question

    Is there a way to do this program without a 2-dim array as
    the second array??

    The output of your code does not show just the numbers that occur most frequently. That is the only output to be printed as I can tell from instructions.

    I do want to print the original array (arr1 in your example) and then the mode - the numbers that come up the most often - must list all numbers that come up as many times as others, if there are more than 1 numbers that are randomly generated the same number of times.

    eg. 100 elements, 1-30 randomly generated
    on average the numbers 1-30 will be generated as elements 3+ times in an array of 100 elements. There is the probability that 2 or more numbers come up the most of equal times, these would all be the mode of an array (string of random numbers)
    3*30 =90 so 10 numbers could come up 4 times and there would be 4 modes to show as output.

    I am not understanding how to print out more than one mode
    (more than 1 number that shows up the most in a 100 element list)


    Please respond soon.

  9. #9
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Is there a way to do this program without a 2-dim array as
    the second array??
    Yes, but you would not be able to sort this array. However if you just want to print out the most frequent numbers you may not have to sort the array, just loop through the array that has been used to count the occurrences looking for the most frequent number and then loop through again printing out all numbers that occur at this frequency. Then you could do the same for other frequencies if required.

  10. #10
    Need Help
    Guest

    looping twice

    okay so to use a 1-dim array;
    need to loop twice; once to count frequency
    once to find the highest frequency and equiv frequency if more than one ???

  11. #11
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    once to find the highest frequency and equiv frequency if more than one ???
    You'll have to loop twice for this because you won't know the highest frequency until you've looped through the entire array. The first loop to find the highest frequency (store this value in a variable) then the second loop to find the other values that occur at this frequency.

  12. #12
    Unregistered
    Guest

    HERE"S CODE ; still have problem

    I got the array created (100 random elements)
    I got the frequency of values calculated (numbers 1-30)
    However, I am needing the number that coincides with the highest frequency of occurring values:

    eg. array1 elements = {1, 4, 5, 5, 6, 4, 3, 10, 5, 4}
    1 occurs 1 time
    4 occurs 3 times
    5 occurs 3 times
    3 occurs 1 time
    10 occurs 1 time
    6 occurs 1 time
    SO: 4 and 5 each occur the most often at 3 times each;
    these would be printed as the output titled MODE of array

    Can I do this part somehow without a 2-dim array????
    I don't get the answers I have been given thus far.
    Sorry.

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    /*****************************************/
    /*  definitions                          */
    /*****************************************/
    
    #define NUM_ELEM 100
    #define RANGE 30
    
                   /***************************/
                   /*    BEGIN OF MAIN        */
                   /***************************/
    int main()
    {
      int array1[NUM_ELEM]={0};    /* declare/initilize arrays */
      int array2[RANGE]={0};
    
      int i,j;                     /* declare int variables */
      int temp, mode;
    
      srand((unsigned)time(NULL));   /* seed random number     */
                                     /* generator              */
    
      printf("here is the array created\n");
                                          /**********************/
        for (i=0;i<NUM_ELEM;i++)          /* create array of    */
          {                               /*   elements         */
            array1[i]=rand()%RANGE+1;     /* and print array    */
            printf("%2d  ",array1[i]);     /**********************/
            if ((i+1)%20==0)
            printf("\n");
          }
    
      printf("\n\n");
                                       /************************/
        for(i=0;i<NUM_ELEM;i++)        /* count frequency of   */
          {                            /* number occurence     */
            array2[array1[i]-1]++;     /************************/
          }
    
    
        for( i = 0; i < RANGE-1; i++ )          /***************/
           { for( j = RANGE-1; j > i; j-- )     /* sort array  */
                if( array2[j] > array2[j-1])    /*of occurences*/
                  {                             /***************/
                    temp = array2[j-1];
                    array2[j-1] = array2[j];
                    array2[j] = temp;
                  }
           }
    
    
        return 0;
    }

  13. #13
    Need Help
    Guest
    ooh, forgot to put my Name in;
    the last post was mine, of course

    anyone able to help me with last couple of questions?????????
    1) finding index of element which would be equal to
    frequency of occurence
    2) needing 1-dim array to do this, instead of 2-dim

    I see that I didn't need to sort anything, I just need to know this:


    if arr1[0]=5 and arr1[22]=5 and arr1[33]=5 and arr[54]=5
    5 occurs 4 times (and the most times, we'll say here)
    then I need from the second array that was counting the frequency , where:

    arr2[0] = 1 << >> first of the values of arr1
    arr2[1] = 2
    arr2[2] = 3
    ...
    arr2[29] = 30 << >> last of the values of arr1

    if arr2[4] represents the value 5 then it's value would be 4 (from example above)

    how do I get the program to convert arr2[4] to say that 5 is the value occuring most often in array1 ???

  14. #14
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    If you just need your program to print out the most frequent occurances then this will do it -

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    /*****************************************/
    /*  definitions                          */
    /*****************************************/
    
    #define NUM_ELEM 100
    #define RANGE 30
    
                   /***************************/
                   /*    BEGIN OF MAIN        */
                   /***************************/
    int main()
    {
      int array1[NUM_ELEM]={0};    /* declare/initilize arrays */
      int array2[RANGE]={0};
    
      int i;                     /* declare int variables */
      int mode;
    
      srand((unsigned)time(NULL));   /* seed random number     */
                                     /* generator              */
    
      printf("here is the array created\n");
                                          /**********************/
        for (i=0;i<NUM_ELEM;i++)          /* create array of    */
          {                               /*   elements         */
            array1[i]=rand()%RANGE+1;     /* and print array    */
            printf("%2d  ",array1[i]);     /**********************/
            if ((i+1)%20==0)
            printf("\n");
          }
    
      printf("\n\n");
                                       /************************/
        for(i=0;i<NUM_ELEM;i++)        /* count frequency of   */
          {                            /* number occurence     */
            array2[array1[i]-1]++;     /************************/
          }
    
    	
    
    	mode =0;
    	for(i=0;i<RANGE;i++)
    	{
    		if (array2[i]>mode)
    		mode = array2[i];
    	}
    
    	for(i=0;i<RANGE;i++)
    	{
    		if(array2[i]==mode)
    		printf("number: %d\toccurance: %d\n",i+1,array2[i]);
    	}
    
            
    
        return 0;
    }
    However I'm not entirely sure what you want (perhaps you could post your homework question in full if this doesn't help). If you need to know the frequency of all the numbers, as an alternative to a 2 dim array you could create an array of structs (each instance storing the number and its frequency). Then sort this array.

  15. #15
    NEED HELP
    Guest

    Thumbs up MUCH THANKS

    Zen, your code worked beautifully. You know I had the idea of what I wanted, but converting it to proper code was not coming to light so easily for me.

    I thank you.

    You should be promoted to Super Moderator !!!

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 08:48 PM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-12-2004, 12:15 AM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. C Filling and Printing a 2-d array
    By Smoot in forum C Programming
    Replies: 3
    Last Post: 11-13-2003, 08:42 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21