2013-04-30 35 views
-1

我的數組對象如下:陣列 - 找對象重複進行幾次連續

10,10,10 
20,23,14 
10,10,10 
10,10,10 
10,10,10 
32,23,42 
32,23,42 
10,10,10 
32,23,23 
32,23,23 

我怎樣才能通過這個陣列,並找出相同的對象依次重複進行幾次,然後添加一個,和它重複的次數?

然後保存狀物體的新數組:

10,10,10,1 
20,23,14,1 
10,10,10,3 
32,23,42,2 
10,10,10,1 
32,23,23,2 

任何幫助,將不勝感激。

謝謝!

+4

爲什麼'的獲得10,10,10''第一和第三的情況下,1運行「的uniq -c」 '但第二例得到',3'?另外,這些對象是字符串嗎? – 2013-04-30 20:45:35

+0

因爲我只關心連續重複。 – objectiveccoder001 2013-04-30 20:46:28

+0

不是對象的總次數。 – objectiveccoder001 2013-04-30 20:46:48

回答

0

試試這個:

NSMutableArray *outArray = [[NSMutableArray alloc] init]; 
for (NSUInteger j = 0; j < [theArray count]; j++) { 
    id object = [theArray objectAtIndex:j]; 
    NSUInteger repeats = 1; 
    while (j + 1 < [theArray count] && [[theArray objectAtIndex:j + 1] isEqual:object]) { 
     j++; 
     repeats++; 
    } 
    [outArray addObject:object]; 
    [outArray addObject:[NSNumber numberWithUnsignedInteger:repeats]]; 
} 
return outArray; 

這也可以在地方做,如果輸入數組是可變的。我把它作爲讀者的練習。

+0

雖然這可行,但你的運行時間是O(J * N)(雖然這裏N = 3,可能會更糟糕) – 2013-04-30 20:51:50

+0

O(J * N),其中J是任何常數仍然是O(N)。任何涉及檢查數組中每個元素的解決方案都將至少爲O(N)。 – 2013-04-30 20:54:51

+0

沒錯,雖然這個例子是不變的,但是看着這個算法的人可以將它應用到變量J – 2013-04-30 20:59:17

0

將每三個整數分解到它自己的數組中(確保它們是字符串)。

然後通過這些陣列中的每一個,並將其輸入到一個NSMutableDictionary迭代,關鍵是串(你的電話號碼),該值是一個計數器(如果看到一次,加1,等...)

保持指向最高關鍵點的指針(如果newCount> highestCountPointer,則highestCountPointer = newCount)

在該迭代結束時,將最高數量的點數添加到數組的末尾。

+0

OP只需要一種運行長度編碼,而不是一個具有計數的唯一值列表。 – 2013-04-30 21:08:41

0

我不是Objective C程序員,所以請原諒任何語言錯誤。類似下面應該做的工作:

NSMutableArray *result = [[NSMutableArray alloc] init]; 
id pending = nil; 
NSUInteger count = 0; 
for (NSUInteger i = 0; i < [theArray count]; i++) { 
    id object = [theArray objectAtIndex:i]; 
    if ([object isEqual:pending]) { 
     count++; 
    } else { 
     if (pending != nil) { 
      [result addObject:[NSString stringWithFormat:@"%@,%d", pending, count]]; 
     } 
     pending = object; 
     count = 1; 
    } 
} 
if (pending != nil) { 
    [result addObject:[NSString stringWithFormat:@"%@,%d", pending, count]]; 
} 
0

只需在命令行:)

+0

OP不尋找唯一的計數,只是一種遊程編碼。 – 2013-04-30 21:07:54

+0

重新格式化「uniq -c」的結果會給你「運行長度編碼」(提示:使用sed或tr) – ElKamina 2013-04-30 21:10:02