我希望在随机生成的数组中找到一行中的重复数字(连续2行,连续3行,......)。我不能比这更进一步:
#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;
}
答案 0 :(得分:0)
您可以使用:
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;
}
答案 1 :(得分:0)
你可以这样做:
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;
}
}
但这并不能解释a
末尾的任何重复。我把它作为锻炼让你自己做。