C++ 从数组中选择n个元素
存在给定的C++ 从数组中选择n个元素,c++,algorithm,C++,Algorithm,存在给定的size>n数组,我们需要从数组中选择n元素数 例如:数组包含112个元素且n=50,因此选择50个数字,使每两个选定数字之间的距离大致相等(当然,除了大小%n==0,不可能等距) 如果有人提出任何可行的想法 Example : array = 1 2 3 4 5 n = 1 output : 1 or any another number depending on proposed algo. n = 2 output : 1 3 or 2 4 or 1 4... n = 3
size>n
数组,我们需要从数组中选择n
元素数
例如:数组包含112个元素且n=50,因此选择50个数字,使每两个选定数字之间的距离大致相等(当然,除了大小%n==0
,不可能等距)
如果有人提出任何可行的想法
Example :
array = 1 2 3 4 5
n = 1
output : 1 or any another number depending on proposed algo.
n = 2
output : 1 3 or 2 4 or 1 4...
n = 3
output : 1 3 5
n = 4
output : 1 3 4 5 or 1 2 4 5
n = 5 :
output 1 2 3 4 5
基本上,在n=1,2,4的情况下,有不止一个可能的组合,所以我需要设计一个算法,以均匀分布的方式选择数字 一种方法是将元素数除以浮点选择中所需的元素数,并使用舍入来确定索引:
double dist = ((double)size) / n;
int *res = new int[n];
for (int i = 0 ; i != n ; i++) {
res[i] = orig[round(dist*i)];
}
对于112
和50
的示例,dist
的值为2.24
,从数组中选择的索引序列为
0 0
1 2
2 4
3 7
4 9
5 11
......
45 101
46 103
47 105
48 108
49 110
数组中的差异或距离?还有其他限制吗。。。例如,例如n个非连续元素?@YSC这是距离。@fritzone我没有理解你?@EmptyData我无法从上面给出的描述中理解问题。请考虑添加一个例子,并对问题进行更清楚的描述,以便我们能够帮助。这是最好的答案,在最后一刻取整。