Frequency of Numbers in a 1D Array

房东的猫 提交于 2019-12-11 07:51:36

问题


its been 6 hours since I have been writing the code but to no avail, I don't no where I am making the mistake but I am making some. Its a frequency output program and output should be like this:

array[8] = {6,1,7,8,6,6,1,9}

Output:

6:3
1:2
7:1
8:1
9:1

But its repeating the same numbers in my code. Any help would be much appreciable.

int array[8] = {6,1,7,8,6,6,1,9};
int store[8];
int a =0;
int b =0;
int c=0;

int d = 0; 
store[d] = array[b];
for (d = 0; d < 8; d++){
  int count=0;
  c = d; 
  b = d; 
  for (int e = 0; e < d; e++){
    if (array[b] == store[e]){
      store[d] = array[b];
      b++;              
      e = 0;            

    }                   
    else   
    {      
      store[d] = array[b]; 
      break;    
    }       
  }        

  for ( int z = 0; z < 7; z++){ 
    if (store[d] == array[z])
    {          
      count++;              

    }                       
  }            
  cout << store[d] << ":" << count << endl;
}

回答1:


I'm not sure what you are trying to do with the arrays. I have tried to follow the logic, but it's hard to see it with all the anonymous variable names. It seems like you are trying to look for duplicates earlier in the array, but the variable e never gets any other value than 0, so you will only be comparing with the first item in the array.

You can just look in the array itself for previous occurances, and once you know that the number is the first occurance, you only need to look for more occurances after it in the array:

int array[8] = {6,1,7,8,6,6,1,9};

for (int i = 0; i < 8; i++) {

  // look to the left in the array if the number was used before
  int found = 0;
  for (int j = 0; j < i; j++) {
    if (array[i] == array[j]) found++;
  }

  // go on if it's the first occurance
  if (found == 0) {

    // we know of one occurance
    int count = 1;

    // look to the right in the array for other occurances
    for (int j = i + 1; j < 8; j++) {
      if (array[i] == array[j]) count++;
    }

    cout << array[i] << ":" << count << endl;
  }
}



回答2:


You may use a map first to store num->frequency and then a multimap to store freqeuncy => num.

Here is the working solution.

#include <map>
#include <algorithm>
#include <iostream>

int main()
{
    int array[8] = {6,1,7,8,6,6,1,9};

    // A map to store num => freq 
    std::map <int, int> freq;

    // A map to store freq(can be duplicate) => num 
    std::multimap <int, int> freqCounts;

    // Store num => frequency
    for (int i = 0 ; i < 8; i++)
    {
        freq[array[i]] += 1;
    }

    // Now Store freq => num
    for(auto const & iter : freq)
    {
        freqCounts.insert (std::pair<int,int>(iter.second, iter.first)); 
    }

    // Print in reverse order i.e. highest frequency first
    for (std::multimap<int,int>::reverse_iterator rit=freqCounts.rbegin(); rit!=freqCounts.rend(); ++rit)
    {
        std::cout << rit->second << " : " << rit->first << '\n';
    }
    return 0;
}



回答3:


You never seem to update the counters. Try this:

int array[8] = {6,1,7,8,6,6,1,9};

unsigned int store[10] = {};    // large enough to hold the largest array value,
                                // initialized to zero

for (int n : array) ++store[n]; // update counts

for (int i = 0; i != 10; ++i)
{
    std::cout << "Frequency of int " << i << " is " << store[i] << "\n";
}

If the set of values that occur is sparse, or includes negatives, or simply does not fit into a dense range of integers nicely, you can replace unsigned int[10] with an associative container, e.g.:

std::map<int, unsigned int> store;

// algorithm as before

for (auto const & p : store)
{
    std::cout << "Frequency of " << p.first << " is " << p.second << "\n";
}



回答4:


I wanted to submit my solution which I think it´s a more easy one:

#include <iostream>
using namespace std;

int main() {
    int n; //number of Elements in the vector
    cin>>n;
    int vec[n]; //vector with all elements
    int v[n];  //vector with Elements without repetition
    int c[n];  // vector which stores the frequency of each element
    for(int i=0; i<n; i++)
        cin>>vec[i];
    int k=0; // number of Elements of the vector without Repetition, in the begining, it has 0 Elements
    int j=0; //logic Counter, could be replaced with bool
    for(int i=0; i<n; i++) {
        for(int h=0; h<=k; h++) {
            if(vec[i]==v[h]) {
                c[h]++;
                j=1;
                break;
            }
        }
//if element i of the original vector is equal to element h of the second vector, then increment the frequency of this element
        if(j==0) { //else if the element is not equal to any of the second vector, the Position of the 2nd vector is filled with the element, which in this case is the first of ist Kind.
            v[k]=vec[i];
            c[k]=1;
            k++;
        } //the number of Elements is increased by one to store another element;
        else {
            j=0;
        }
    }
    cout<<endl<<endl;
    for(int i=0; i<k; i++)
        cout<<v[i]<<":"<<c[i]<<endl;
    return 0;
}



回答5:


#include<iostream>
#include<conio.h>
using namespace std;
main()
{   int count[10],key[10],n=10,m;
    int i,j,k,temp;
    cout<<"Enter The Size Of Array:-\n";
    cin>>n;
    int a[n];
    cout<<"Enter The Elements in Array:-\n";
    for(i=0; i<n; i++)
        cin>>a[i];
    for(i=0; i<n; i++)
        for(j=0; j<n-1; j++)
        {   if(a[j]>a[j+1])
            {   temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    for(i=0; i<n; i++)
        cout<<a[i]<<"\t";
    for(i=0,k=0; i<n; k++)
    {   count[k]=0;
        key[k]=a[i];
        for(j=i; j<n; j++)
        {   if(a[i]==a[j])
                count[k]++;
        }
        i=i+count[k];
    }
    for(i=0; i<k; i++)
        cout<<endl<<key[i]<<" Occurred "<<count[i]<<" Times\n";
    getch();
}



回答6:


/**
 * The methods counts the frequency of each element in an array.
 * 
 * Approach: The method checks if the element is already present in the <strong>Map of frequency</strong>.
 * If it is not present, add it to the map with the frequency 1 else put it in the map with 
 * an increment by one of it's existing frequency.
 * 
 * @param arr list of elements
 * @return frequency of each elements
 */
public static Map<Integer, Integer> countFrequency(int[] arr) {
    Map<Integer, Integer> frequency= new HashMap<Integer, Integer>();
    for(int i = 0; i < arr.length; i++) {
        if(frequency.get(arr[i])==null) {
            frequency.put(arr[i], 1);
        }
        else {
            frequency.put(arr[i],frequency.get(arr[i])+1);
        }
    }
    System.out.println("\nMap: "+frequency);
    return frequency;
}


来源:https://stackoverflow.com/questions/26566265/frequency-of-numbers-in-a-1d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!