如何计算数字 x 的频率
How to count the frequency of the number x
我想打印第一个数到 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;
}
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 如何用数字处理log(0)
- 在指针的帮助下,文本文件中单词的频率
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 如何计算数字 x 的频率
- C++:输出文件中ASCII字符计数频率的结果时出现的奇怪数字
- 来自单个数字输入的Arduino读取脉冲宽度频率和占空比
- 我如何找到给定数字的频率到一个数组中的范围
- 获取给定数字集中具有相同数字频率的组数
- 1D阵列中数字的频率
- 提取计数器注册某个数字的频率
- 一种有效的间隔内数字频率计数算法
- 给定一个范围,我必须计算数组中数字的频率.给定的解决方案是否有效