【问题标题】:Print amount of repeated numbers in array c++在数组c ++中打印重复数字的数量
【发布时间】:2016-12-07 22:15:08
【问题描述】:

我想知道如何从随机生成的数组中打印重复数字的数量,数组大小为 10,数字范围为 1 - 10。

示例: 数组1:1 7 6 5 6 7 8 10 9 8

图案数量:3

(因为它包括;2 个六、2 个七、2 个八)

到目前为止,我已经完成了我的代码

#include <iostream>
#include <iomanip>
#include <string>
#include <time.h>
#include "Source.h"
#include <algorithm>   
using namespace std;

void main()
{
    //START OF PROGRAM CODE\\

    //Declaritions\\

    const int ArraySize = 10;
    int arrayMain[ArraySize];
    int array1[ArraySize];
    int i = 0;
    int j = 0;
    int k = 0;


    //End of Declairations\\

    //Store Random Number in Array\\

    srand((unsigned)time(0));

    for (i = 0; i < 10; i++)
     {
        arrayMain[i] = (rand() % 10) + 1;
        array1[i] = arrayMain[i];  //Copy mainarray to array1


     }  

    for (j = 0; j != ArraySize; j++)
     {
        sort(array1, array1 + ArraySize); //Sort the array

     }


        //End of Store Random Number in Array\\
        //Program Output\\


    cout << "ArrayMain: " << arrayMain[0] << " " << arrayMain[1] << " " << arrayMain[2] << " " << arrayMain[3] << " " << arrayMain[4] << " " << arrayMain[5] << " " << arrayMain[6] << " " << arrayMain[7] << " " << arrayMain[8] << " " << arrayMain[9] << " " << endl;
    cout << "Array1: " << array1[0] << " " << array1[1] << " " << array1[2] << " " << array1[3] << " " << array1[4] << " " << array1[5] << " " << array1[6] << " " << array1[7] << " " << array1[8] << " " << array1[9] << " " << endl;
    //cout << "Number of Patterns: " << <DATA TO INPUT> << endl;

    //END OF PROGRAM CODE\\


}

【问题讨论】:

  • 除了排序,你的代码没有做太多的计数。如果性能不是问题,您可以使用计数映射:对数组中的每个条目执行 countMap[entry]++,因此映射中值大于 1 的条目数就是您所追求的数字。
  • 只使用桶排序。
  • 如果您允许数字重复,如何仅生成 1-10 范围内的 10 个数字不符合您的需求?

标签: c++ arrays count duplicates


【解决方案1】:

有一个非常简单的模式。您可以使用大小等于可能随机数范围的数组(我将使用向量)

//creates a vector ArraySize big with all elements initialized to 0
std::vector<int> results(ArraySize, 0);

然后,遍历你的循环并使用随机数作为索引并增加值

for(int i = 0; i < 10; i++)
  results[(rand() % 10)]++;

最后,计算有多少种模式

std::cout << "Number of patterns: ";
std::cout << std::count_if(results.begin(), results.end(), [](int i){return i > 1;});
std::cout << std::endl;

【讨论】:

  • 我在对该问题的评论中提到的地图是该答案的一般情况。对于从 1 到 10 的数字,这个答案更好。
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
相关资源
最近更新 更多