Extract the same elements from Arr into a decimal group, and then place the decimal group in a large array of Dataarry
Nsmutablearray *arr =[nsmutablearray arraywithobjects:@ "1", @ "2", @ "1", @ "3", @ "2", @ "2", @ "4", @ "1", @ "2", @ "2", @ "2", @ "2" , nil];
1. Create an array Dataarry
Nsmutablearray *dataarr = [Nsmutablearray array];
2. Use two for loops to traverse arr
Method One,
for (Nsinteger i = 0; i<arr.count; i++) {
Nsmutablearray *temparr = [Nsmutablearray array];
NSString *str = Arr[i];
[Temparr ADDOBJECT:STR];
for (Nsinteger j = i+1; j<arr.count; j + +) {
NSString *tempstr = Arr[j];
if ([str isequal:tempstr]) {
[Temparr ADDOBJECT:TEMPSTR];
[Arr Removeobjectatindex:j]; Determine if two values are added to the Temparr, and then delete this element
}
}
[Dataarr Addobject:temparr];
}
Output result:dataarry:[[1,1,1],[2,2,2,2],[3],[2,2],[4],[2]]
The result is not what we want, the problem is that the number of elements in Arr will change, and the value of J is incremented in order, then we will see an error when judging by the element subscript.
Solution: 1, put the loop of J into reverse
for (Nsinteger j = arr.count-1; j>i; j--)
{
}
2. Do not delete elements in the For loop, remove all elements from the entire Temparr array in arr outside of the For loop, and let i-1, always keep traversing from the beginning
for (Nsinteger i = 0; i<arr.count; i++) {
Nsmutablearray *temparr = [Nsmutablearray array];
NSString *str = Arr[i];
[Temparr ADDOBJECT:STR];
for (Nsinteger j = arr.count-1; j>i; j--) {
NSString *tempstr = Arr[j];
if ([str isequal:tempstr]) {
[Temparr ADDOBJECT:TEMPSTR];
}
}
[Dataarr Addobject:temparr];
if (temparr.count>1) {
[Arr Removeobjectsinarray:temparr];
I-=1;
}
NSLog (@ "dataarry:%@", Dataarr);
Extract the same elements in the array