查找c++数组中的最频繁值和中位数
Find most frequent and median values in array C++
我想通过使用c++找到给定数组的最频繁值和中位数。我假设我有一个浮点数组,如
float *LRArr=new LRArr[1000];
数组由随机浮点数填充。
std::default_random_engine generator;
generator.seed( rd() );
std::uniform_real_distribution<> distribution(0, 10);
for(int j=0;j<1000;j++)
{
LRArr[j]=distribution(generator)
}
现在我想要得到数组中出现频率最高的值。但这需要很多时间。你能告诉我用C或c++实现它的更快的方法吗?我假设我有LRArr
,如
LRArr={0.1,1.2,6.5,6.5,4.5,6.5}
==>output is: 6.5 and median 5.5
这是我的方式:
float getMostFreq(float* LRArr;int sizeLRArr)
{
int count = 1;
int currentIndex = 0;
for (int i = 1; i < sizeLRArr; i++)
{
if (LRArr[i] == LRArr[currentIndex])
count++;
else
count--;
if (count == 0)
{
currentIndex = i;
count = 1;
}
}
mostFreq = LRArr[currentIndex];
return mostFreq;
}
计算数组中float值出现频率的一种方法是计算直方图并对其排序。但是你应该考虑到你的值的范围应该被定义。这样,准确率取决于直方图箱的数量:
#include <algorithm>
#define histogramCount 10000
#define upperRange 1000
#define lowerRange 0
class histogram_data
{
public:
int frequency;
int index;
};
bool SortPredicate(const histogram_data& d1, const histogram_data& d2)
{
return d1.frequency> d2.frequency;
}
void computeHistogram(float * array, int len)
{
std::vector<histogram_data> histogram;
for(int i=0;i<histogramCount;i++)
{
histogram_data hdata;
hdata.frequency=0;
hdata.index=i;
histogram.push_back(hdata);
}
for(int i=0;i<len;i++)
{
histogram[(array[i]/(upperRange-lowerRange))*(histogramCount-1)].frequency++;
}
//sorting the histogram in descending order
std::sort(histogram.begin(),histogram.end(),SortPredicate);
}
现在数值的频率按降序存储在直方图中。因此,最常见的值可以通过以下方式获得:
float mostFrequent = ((float)histogram[0].index/(float)(histogramCount-1))*(upperRange-lowerRange);
相关文章:
- 在 1.5 秒内找到 3 到 4 个不同整数的中位数超过 2000 万
- 十进制的中位数是多少?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 使用 boost::累加器::统计来查找数组的中位数
- 从向量中提取最小值、最大值和中位数的最有效方法是什么
- 如果方法是常量,如何找到向量的中位数?
- 在C++中实现两个大小相等的排序数组的中位数
- 查找一组循环数据的中位数
- 为什么我的中位数快速选择算法segfault
- 是否可以实施中位数的中位数intreselect而没有掉期或堆的分配
- 两个分类阵列的中位数不同
- C++平均值和中位数绝对偏差返回相同的奇怪符号
- 通过 uva 的中位数程序
- 找到二叉搜索树的中位数,C++
- 双向链表的中位数
- 通过 C 加加号中的函数查找中位数
- C++:平均中位数和众数
- 返回带有 void 函数的排序数组以查找中位数
- 使用计数选择 (C++) 运行中位数算法
- 运行常量大小数组的中位数