2016-02-26 153 views
-1

給出size > n的數組,我們需要從數組中選擇n個元素。從數組中選擇n個元素

例如:數組包含112元件和n = 50,所以選擇50號,使得每兩個選定數目之間的距離是或多或少相等(距離相等是不可能的,當然除了size%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 

基本上在正的情況下= 1,2,4有多於一個可能的組合,所以我需要設計一種算法中這將挑uequally分佈的方式編號。

+1

數組中的差異或距離? – YSC

+0

還有什麼限制? ...例如n個不連續的元素? – fritzone

+0

@YSC這是距離。 – EmptyData

回答

3

一種方法是除以在選擇所需的元素的數量的元件的數目在浮點,以及使用舍入來確定指數:

double dist = ((double)size)/n; 
int *res = new int[n]; 
for (int i = 0 ; i != n ; i++) { 
    res[i] = orig[round(dist*i)]; 
} 

爲了您的11250值例如的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 
+0

如何,你_did_得到的問題。它是最好的答案,在最後時刻四捨五入。 – YSC