C++ 在随机生成的数组中查找重复的连续数字
我想在随机生成的数组中查找一行中的重复数字(2行,3行,…)。除此之外,我再也做不到了:C++ 在随机生成的数组中查找重复的连续数字,c++,arrays,windows,C++,Arrays,Windows,我想在随机生成的数组中查找一行中的重复数字(2行,3行,…)。除此之外,我再也做不到了: #include "stdafx.h" #include <iostream> #include <cstring> #include <ctime> #include <array> #include <algorithm> using namespace std; int main() { srand(time(NULL));
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <ctime>
#include <array>
#include <algorithm>
using namespace std;
int main()
{
srand(time(NULL));
const int velikostPolja = 100;
int a[velikostPolja];
int y = 0;
int x = 0;
for (int i = 0; i < velikostPolja; i++)
{
a[i] = rand() % 10;
cout << a[i];
}
cout << endl;
for (int i = 0; i < velikostPolja; i++)
{
if (a[i] == a[i + 1])
x++;
}
cout << endl;
cout << "Two times repated in row: " << x << endl;
system("pause");
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
srand(时间(空));
常数int velikostPolja=100;
INTA[velikostPolja];
int y=0;
int x=0;
对于(int i=0;i
template <typename IT>
std::size_t count_repetition(IT begin, IT end, std::size_t count)
{
std::size_t res = 0;
auto it = begin;
while (it != end) {
it = std::adjacent_find(it, end);
if (it == end){
return res;
}
const auto it2 = std::find_if(it, end, [it](const auto& e) { return e != *it; });
const auto dist = std::distance(it, it2);
if (count <= dist) {
// how to count 2-repetition for {a, a, a, a}
#if 0
++res; // Count only as 1
#else
res += dist + 1 - count; // count as 3
#endif
}
it = it2;
}
return res;
}
模板
std::size\u t count\u重复(开始、结束、std::size\u t count)
{
标准:尺寸=0;
自动it=开始;
while(it!=结束){
it=std::相邻的查找(it,end);
if(it==end){
返回res;
}
const auto it2=std::find_if(it,end,[it](const auto&e){returne!=*it;});
const auto dist=std::distance(it,it2);
如果(count您可以这样做:
int count[velikostPolja] = { 0 };
int c = 0;
for (int i = 1; i < velikostPolja; i++)
{
if (a[i] == a[i - 1])
{
++c;
}
else
{
++count[c];
c = 0;
}
}
for (int i = 1; i < velikostPolja; i++)
{
if (count[i])
{
cout << i + 1 << " times repeated in row: " << count[i] << endl;
}
}
int count[velikostPolja]={0};
int c=0;
对于(int i=1;i cout提示:对您将有权访问的数组进行排序,使其超出a[i]==a[i+1]
,因为您不修改范围。@RichardCriten,他为什么要对数组进行排序?@RichardCriten,他想相邻数数重复的数字,所以一次就可以了。他已经实现了连续2次,但不是连续3次。我的意思是,您应该对(int I=0;I+1
。