Count number of occurrences of a digit within a string

别来无恙 提交于 2019-12-02 09:08:22

问题


So I'm trying to count the number of occurrences of each digit within an array.

My code I've got so far looks like the following:

#include <stdio.h>
#include <string.h>

int main()
{
  int numbers [10]= {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
  int count = 0;

  for(int i = 0; i < 10; i++)
  {
    for (int j = 0; j < 10; j++)
    {
      if (numbers[i] == numbers[j])
      {
        count++;
      }
    }
    printf("Number %d has occured %d many times \n", numbers[i], count);
    count = 0;

  }
} 

Only the output I get is the following:

Number: 1       Occurence: 2
Number: 4       Occurence: 1
Number: 5       Occurence: 3
Number: 5       Occurence: 3
Number: 5       Occurence: 3
Number: 6       Occurence: 2
Number: 6       Occurence: 2
Number: 3       Occurence: 1
Number: 2       Occurence: 1
Number: 1       Occurence: 2 

I only want to count the occurrence of EACH digit, it seems to be counting duplicates.

How can I correct this code? Can someone point me in the right direction.

Many thanks

Alonso


回答1:


Consider this modified code:

#include <stdio.h>
#include <string.h>

int main()
{
  int numbers [10]= {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
  int count = 0;

  for(int i = 0; i < 10; i++) { //i = current digit
    for (int j = 0; j < 10; j++) { //j = index in array
      if (i == numbers[j]) {
        count++;
      }
    }
    printf("Number %d has occured %d times \n", i, count);
    count = 0;
  }
}

Output:

Number 0 has occured 0 times 
Number 1 has occured 2 times 
Number 2 has occured 1 times 
Number 3 has occured 1 times 
Number 4 has occured 1 times 
Number 5 has occured 3 times 
Number 6 has occured 2 times 
Number 7 has occured 0 times 
Number 8 has occured 0 times 
Number 9 has occured 0 times 

You were counting how often each digit occuring in the array (including duplicate digits in the array) occured.




回答2:


You are going to need to arrays - one for the count (result) and one for the input. You should increment the index in the count array as you loop over the input numbers. I couldn't resist actually writing the code so, here you go, the following should work IN C++

#include <stdio.h>
#include <string.h>

int main()
{
  int inputNumbers [] = {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
  int resultCount [] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int countNumbers = sizeof(inputNumbers) / sizeof(inputNumbers[0]);

  for(int i = 0; i < countNumbers; i++)
  {
     resultCount[inputNumbers[i]]++;
  }

  for(int i = 0; i < countNumbers; i++)
  {
    printf("Number %d has occured %d times \n", i, resultCount[i]);
  }
}

Hope that helps.



来源:https://stackoverflow.com/questions/20446042/count-number-of-occurrences-of-a-digit-within-a-string

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