Frequency of Numbers in a 1D Array

前端 未结 6 414
清酒与你
清酒与你 2021-01-27 03:54

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 sh

6条回答
  •  走了就别回头了
    2021-01-27 04:09

    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;
      }
    }
    

提交回复
热议问题