2012-01-29 97 views
1

我有一個大小爲n的NSMutableArray urlArray,我想從數組中的元素總數中隨機選擇4個這樣的URL。將NSNumbers數組重新排序並轉換爲整數

但是我不想直接洗牌urlArray,我更願意做一個「indexArray」 [0 ...(N-1)] &洗牌這些,&然後使用洗牌的前4種元素indexArray來決定我從urlArray中選擇哪些元素。

首先,我創建了indexArray如下:

for (int i = 0; i < numberOfStems; i++) { 

    [indexArray addObject:[NSNumber numberWithInteger:i]]; 

} 

這讓我重新洗牌我indexArray,到目前爲止,一切順利。因爲我使用了 [NSNumber numberWithInteger:i]方法,混洗索引數組中的元素是NSNumbers。

有沒有辦法將indexArray中的NSNumber對象轉換爲ints?

我試圖使用intValue函數,但這似乎並不是我所需要的。

我也嘗試創建一個c樣式的數組,但這並沒有那麼成功 - 如果可能的話,我想堅持使用objective-c語法。

任何想法?任何提示讚賞:)

+0

它的intValue。 – dasblinkenlight 2012-01-29 22:45:05

+3

您是否試過'[[indexArray objectAtIndex:i] integerValue]'?你得到的結果是你沒有想到的? – user1118321 2012-01-29 22:45:44

+0

我嘗試了intValue,但是返回的數字(類似於我記得的972378)表明了一個錯誤,此時我以爲我處於錯誤的軌道上。你的建議確實奏效,所以非常感謝。 – Octave1 2012-01-30 13:55:55

回答

2

爲什麼你不只是創建一個正常的c數組,然後洗牌,然後使用數組中的前四個整數作爲隨機索引?

int* index = malloc(numberOfStems*sizeof(int)); 
for (int i = 0; i < numberOfStems; ++i) 
{ 
    index[i] = i; 
} 

for (int i = numberOfStems - 1; i > 0; --i) 
{ 
    int randomIndex = arc4random() % i; 
    int tmp = index[i]; 
    index[i] = index[randomIndex]; 
    index[randomIndex] = tmp; 
} 

現在使用索引來訪問URL的

編輯:更新算法(雖然不是真的涉及到OP問題)

+2

你應該總是使用'arc4random()'而不是'rand()',因爲它的結果更多(僞)隨機。 – 2012-01-29 22:59:40

+0

混洗階段不正確,會產生有偏差的結果。不過,[做正確](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm)並不複雜得多。 – 2012-01-29 23:19:26

+0

事實證明,這是我的解決方案最優雅的方式,感謝您的幫助。 – Octave1 2012-01-30 14:10:01

2

對於只存儲整數的臨時數組在相對較短的任務後被拋棄,我肯定會更喜歡一個C風格的數組:這將避免大量的開銷,也是簡單閱讀。

int *array = (int*)malloc(sizeof(int)*numberOfStems); 
for (int i = 0 ; i != numberOfStems ; i++) { 
    array[i] = i; 
} 
// Do the shuffle 
// Pick first four, and do whatever you need to do 
// ... 
// Now that you are done with the array, do not forget to free it: 
free(array); 
+1

如果在一個函數/方法中創建(小的)C數組,並且在該函數/方法返回之後不需要更改'malloc'並使用'alloca'並刪除'free' - 'alloca''對象會自動釋放當調用函數/方法返回時。 – CRD 2012-01-30 02:46:24