Extract the same elements in the array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.