5

我正在研究 SQLite,我编写了一个查询,它返回两个数组 ItemsArray 和 CustomersIDArray:

ItemsArray
Element at Index 0 = Off White,
Element at Index 1 = Fan,
Element at Index 2 = Off White,
Element at Index 3 = Delux,
Element at Index 4 = Fan

CustomerIDArray 
Element at Index 0 = 1,
Element at Index 1 = 2,
Element at Index 2 = 2,
Element at Index 3 = 3,
Element at Index 4 = 4

我想要这样的结果 Off White = 2 (count) , Fan = 2 (count) and Delux = 1; 和结果数组,

Result Array 
Element at Index 0 = Off White,
Element at Index 1 = Fan,
Element at Index 2 = Delux

实际上我想要第一个数组中的重复计数,但 CustomerArray 的值不能相同。请通过逻辑或代码帮助我。

4

3 回答 3

3
-(NSMutableArray *)getCountAndRemoveMultiples:(NSMutableArray *)array{

    NSMutableArray *newArray = [[NSMutableArray alloc]initWithArray:(NSArray *)array];
    NSMutableArray *countArray = [NSMutableArray new];
    int countInt = 1;
    for (int i = 0; i < newArray.count; ++i) {
        NSString *string = [newArray objectAtIndex:i];
        for (int j = i+1; j < newArray.count; ++j) {
            if ([string isEqualToString:[newArray objectAtIndex:j]]) {
                [newArray removeObjectAtIndex:j];
                countInt++;
            }
        }
        [countArray addObject:[NSNumber numberWithInt:countInt]];
        countInt = 1;
    }
    NSMutableArray *finalArray = [[NSMutableArray alloc] initWithObjects:newArray, countArray, nil];
    NSLog(@"%@", finalArray);
    return finalArray;

}
- (IBAction)getArrayInfo:(id)sender {
    NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:@"Off White", @"Fan", @"Off White", @"Deluxe", @"Fan", nil];
    NSMutableArray *godArray = [self getCountAndRemoveMultiples:myArray];
    NSLog(@"Array from this end = %@", godArray);
}

我刚刚设置了 -getArrayInfo 来测试它。工作正常。如您所见,您要显示的数组将位于 index:0 处,而 countArray 位于 index:1 处。

于 2012-04-23T19:06:21.600 回答
2

NSCountedSet像下面这样使用

NSMutableArray *ary_res = [[NSMutableArray alloc] init];
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"11",@"13",@"34",@"9",@"13",@"34",@"9",@"2",nil];
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
    for(id name in set)
    {
        if([set countForObject:name]==2)
            [ary_res addObject:name];
    }
    //
    NSLog(@"%@",ary_res);
于 2012-04-23T12:58:34.093 回答
0

试试这个:

NSArray *copy = [ItemsArray copy];

NSInteger index = [copy count] - 1;

for (id object in [copy reverseObjectEnumerator]) {

    if ([ItemsArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [ItemsArray removeObjectAtIndex:index];
    }
    index--;
}
于 2012-04-23T12:40:42.250 回答