如何计算数字 x 的频率

How to count the frequency of the number x

本文关键字:数字 频率 计算 何计算      更新时间:2023-10-16

我想打印第一个数到 4 的数字,例如,我有这个随机函数,我想看到第一个数到 4 次的数字。 所以这是第一个打印自己 4 次的数字。例如:

int n;
int count1 = 0;
int count2 = 0;
int count3 = 0;
while (true) {
cout << "Enter a number btween 1-3" << endl;
cin >> n;
if (n == 1) {
count1++;
}
if (n == 2) {
count2++;
}
if (n == 3) {
count3++;
}
if (count1 == 4) {
cout << "You printed the number 1 4 times!";
break;
}
if (count2 == 4) {
cout << "You printed the number 2 4 times!";
break;
}
if (count3 == 4) {
cout << "You printed the number 3 4 times!";
break;
}

但是,如果是 1-1000 个数字而不仅仅是 1-3,我会怎么做?

我想这样做,但是在一个随机函数上 - 该数字计数的第一个数字是 4 倍打印数字 -

int fun() {
srand(time(NULL));
return rand() % 3;
}

然后我想在主要情况下做第一个数字,例如 4 次打印这个数字。

我尝试做这样的事情:

for (int i = 0; i < 31; i++) {
arr[fun()]++;
cout << arr[fun()];
if (arr[fun()] == 4) {
cout << arr[fun()];
}
}

为此,您将使用集合(例如向量),而不是一千个单独的变量:-)

首先,如果你想要范围内的随机数1..3,你会使用(rand() % 3) + 1.但是,您可以使用范围0..n-1而不是1..n,只需在循环后调整值即可。

第一步是创建每个数字的计数并将其初始化为零:

const int SZ = 1000;
std::vector<int> count(SZ, 0);

然后,您的循环只会生成随机数并调整相关计数,直到其中一个达到目标值:

int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit infinite loop when one of them reaches four.
}

然后,您只需简单地输出首先达到四个的那个。请注意,由于我们正在做0..999,我们将其映射到1.1000

std::cout << ++num << " reached a count of four firstn";

如下所示的完整程序:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(nullptr));
const int SZ = 1000;
std::vector<int> count(SZ, 0);
int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit loop when one of them reaches four.
}
std::cout << ++num << " reached a count of four firstn";
}

它的示例运行(确保延迟,以便随机数生成器获得不同的种子):

>> for i in {1..10} ; do sleep 1 ; ./testprog ; done )
296 reached a count of four first
520 reached a count of four first
205 reached a count of four first
239 reached a count of four first
822 reached a count of four first
260 reached a count of four first
421 reached a count of four first
444 reached a count of four first
21 reached a count of four first
92 reached a count of four first

最后一个答案超出了范围。我的答案是只使用数组

while(1) {
int f = rand() % 3;
count[f]++;
cout << f << endl;
if (count[f] == 4) {
cout <<"4 times" <<f;
break;
}
}