简体   繁体   English

计算数组中的位数(c ++)

[英]Count Number of Digits in an array (c++)

let's say I have an array arr[5]={5,2,3,2,5} and i wrote following program for it假设我有一个数组 arr[5]={5,2,3,2,5} 并且我为它编写了以下程序

#include <iostream>
using namespace std;
int main()
{
  int n;
  cout<<"Enter Length of Elements= ";
  cin>>n;
  int arr[50];
  for(int i=0;i<n;i++)
  {
      cout<<"Enter Number=";
      cin>>arr[i];
  }
  for(int i=0;i<n;i++)
  {
      int countNum=1;


      for(int j=i+1;j<n;j++)
      {
          if(arr[i]==arr[j])
          {
              if(i>0)
              {
                  int countNum2=0;


                  for(int k=0;k>i;k++)
                  {
                      //bool repeat=false;

                      if(arr[i]==arr[k])
                      {
                        //repeat=false;
                      }
                      else
                      {
                          countNum2++;
                      }
                  }
                  if(countNum2==i)
                  {
                     countNum++;
                  }
              }
              else
              {
                countNum++;
              }
          }
          else
          {
              for(int k=0;k<i;k++)
              {
                  if(arr[k]==arr[i])
                  {

                  }
                  else
                  {
                      countNum=1;
                  }

              }
          }

      }
      cout<<arr[i]<<" has appeared "<<countNum<< "Times"<<endl;

  }

    return 0;
}

but why I am getting 5 has appeared 2 Times但为什么我得到 5 出现了 2 次

2 has appeared 1 Time 2 出现了 1 次

3 has appeared 1 Time 3 出现了 1 次

2 has appeared 1 Time 2 出现了 1 次

5 has appeared 1 Time 5 出现了 1 次

instead of代替

5 has appeared 2 Times 5 出现了 2 次

2 has appeared 2 Times 2 出现了 2 次

3 has appeared 1 Times 3 出现了 1 次

so how to fix my program help!那么如何修复我的程序帮助!

The problem with your code is that you don't remove the duplicates or assign an array which effectively stores the count of each unique element in your array.您的代码的问题是您没有删除重复项或分配一个有效存储数组中每个唯一元素的计数的数组。

Also the use of so many loops is completely unnecessary.此外,完全没有必要使用这么多循环。

You just need to implement two loops, outer one going through all the elements and the inner one checking for dupes first (using an array to check frequency/occurence status) and counting appearance of each element seperately with a variable used as a counter.您只需要实现两个循环,外部循环遍历所有元素,内部循环首先检查重复项(使用数组检查频率/发生状态)并使用用作计数器的变量分别计算每个元素的出现。

Set a counter array (with the corresponding size of your taken array) with a specific value (say zero) and change that value when same element occurs while traversing the array, to trigger not to count for that value again.使用特定值(例如零)设置一个计数器数组(具有所取数组的相应大小),并在遍历数组时发生相同元素时更改该值,以触发不再计算该值。

Then transfer the count value from the counter variable to the counter array (the one which we set and which distinguishes between duplicates) each time the inner loop finishes iterating over the whole array.然后每次内部循环完成对整个数组的迭代时,将计数值从计数器变量传输到计数器数组(我们设置的并且区分重复项的数组)。 (ie place it after the values are counted) (即在计算值之后放置它)

With a little bit of modification, your code will work as you would want it to:稍作修改,您的代码将按照您的意愿工作:

#include <iostream>
using namespace std;
int main()
{
  int n;
  cout<<"Enter Length of Elements = ";
  cin>>n;
  int arr[50];
  for(int i=0;i<n;i++)
  {
      cout<<"Enter Number = ";
      cin>>arr[i];
  }

  int counter[50];
  for(int i=0; i<n; i++)
    counter[i]=0;

    // Our counter variable, but counts will be transferred to count[] later on:
    int tempcount;

    for(int i=0; i<n; i++)
    {   // Each distinct element occurs once atleast so initialize to one:
        tempcount = 1;
        for(int j=i+1; j<n; j++)
        {
            // If dupe is found: 
            if(arr[i]==arr[j])
            {
                tempcount++;

                // Ensuring not to count frequency of same element again:
                counter[j] = 1;
            }
        }

        // If occurence of current element is not counted before:
        if(counter[i] != 1)
            counter[i] = tempcount;
    }

    for(int i=0; i<n; i++)
    {
        if(counter[i] != 0)
            printf("%d has appeared %d times.\n", arr[i], counter[i]);
    }
 return 0;
}

I used a variable tempcount to count occurence of each element and a zero-initialized array count to get the dupes checked (by setting it to 1 for a duplicate entry, and not counting it if it qualifies as 1) first.我使用一个变量tempcount来计算每个元素的出现次数,并使用一个初始化为零的数组count来检查重复项(通过将其设置为 1 来表示重复条目,如果它符合 1 则不计算它)首先。 Then I transferred the counted occurence values to counter[] from tempcount at each outer loop iteration.然后我在每次外循环迭代时将计数的出现值从tempcount转移到counter[] (for all the unique elements) (对于所有独特的元素)

That's what you exactly need (amount of each number in array):这正是您所需要的(数组中每个数字的数量):

// we'll store amounts of numbers like key-value pairs.
// std::map does exactly what we need. As a key we will
// store a number and as a key - corresponding counter
std::map<int, size_t> digit_count;

// it is simpler for explanation to have our
// array on stack, because it helps us not to
// think about some language-specific things
// like memory management and focus on the algorithm
const int arr[] = { 5, 2, 3, 2, 5 };

// iterate over each element in array
for(const auto elem : arr) 
{
    // operator[] of std::map creates default-initialized
    // element at the first access. For size_t it is 0.
    // So we can just add 1 at each appearance of the number 
    // in array to its counter.
    digit_count[elem] += 1;
}

// Now just iterate over all elements in our container and
// print result. std::map's iterator is a pair, which first element
// is a key (our number in array) and second element is a value
// (corresponding counter)
for(const auto& elem : digit_count) {
    std::cout << elem.first << " appeared " << elem.second << " times\n";
}

https://godbolt.org/z/_WTvAm https://godbolt.org/z/_WTvAm

Well, let's write some basic code, but firstly let's consider an algorithm (it is not the most efficient one, but more understandable):好吧,让我们写一些基本的代码,但首先让我们考虑一个算法(它不是最有效的,但更容易理解):

The most understandable way is to iterate over each number in array and increment some corresponding counter by one.最容易理解的方法是遍历数组中的每个数字并将一些相应的计数器加一。 Let it be a pair with the first element to be our number and the second to be a counter:让它成为一对,第一个元素是我们的数字,第二个是计数器:

struct pair {
    int number;
    int counter;
};

Other part of algorithm will be explained in code below算法的其他部分将在下面的代码中解释

// Say that we know an array length and its elements
size_t length = // user-defined, typed by user, etc.
int* arr = new int[length];
// input elements

// There will be no more, than length different numbers
pair* counts = new pair[length];

// Initialize counters
// Each counte will be initialized to zero explicitly (but it is not obligatory,
// because in struct each field is initialized by it's default
// value implicitly)
for(size_t i = 0; i < length; i++) {
    counts[i].counter = 0;
}

// Iterate over each element in array: arr[i]
for(size_t i = 0; i < length; i++)
{
    // Now we need to find corresponding counter in our counters.
    size_t index_of_counter = 0;

    // Corresponding counter is the first counter with 0 value (in case when
    // we meet current number for the first time) or the counter that have
    // the corresponding value equal to arr[i]
    for(; counts[index_of_counter].counter != 0 && counts[index_of_counter].number != arr[i]; index_of_counter++)
        ; // Do nothing here - index_of_counter is incrementing in loop-statement

    // We found an index of our counter
    // Let's assign the value (it will assign a value
    // to newly initialized pair and won't change anything
    // in case of already existing value).
    counts[index_of_counter].number = arr[i];

    // Increment our counter. It'll became 1 in case of new
    // counter, because of zero assigned to it a bit above.
    counts[index_of_counter].counter += 1;
}

// Now let's iterate over all counters until we reach the first
// containing zero (it means that this counter and all after it are not used)
for(size_t i = 0; i < length && counts[i].counter > 0; i++) {
    std::cout << counts[i].number << " appeared " << counts[i].counter << " times\n";
}

// correctly delete dynamically allocated memory
delete[] counts;
delete[] arr;

https://godbolt.org/z/hN33Pn https://godbolt.org/z/hN33Pn

Moreover it is exactly the same solution like with std::map (the same idea), so I hope it can help you to understand, how the first solution works inside此外,它与std::map完全相同的解决方案(相同的想法),所以我希望它可以帮助您理解第一个解决方案如何在内部工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM