2013-11-21 53 views
-3

我想知道是否有人能够提供给我一些有效的示例代码,请选择数组中的前3个元素?排列中最常见的元素

我的数组只包含一个日期列表,我想要做的是选择包含在其中的前3个日期。

我见过一些返回常见元素的例子,但没有什么会给我一个前3名单。

因此,如果这是我的数组的内容:

2013年1月1日,2013年1月1日,2013年1月1日,2013年1月2日,2013年1月2日,01/02/2013,01/03/2013,01/03/2013,22/05/2013,23/05/2013,27/05/2013,01/06/2013,07/07/2013,12/08/2013

那么我预计前3日期出来为:

2013年1月1日,2013年1月2日,2013年1月3日

任何帮助将非常感激。

+0

您可以创建的NSSet,然后循环直到计数出现... –

+0

这些日期('NSDate'对象)或字符串('NSString'对象)? – trojanfoe

+1

-1你用错误的需求描述误导了我。根据你的个人资料,我应该预料到这一点:-)“我想要做的是挑选前三名日期”是不明确的。 – trojanfoe

回答

0

花了30分钟找到一个解决方案,找到最多3个值...

有一个尝试:

NSArray *[email protected][@"01/01/2013", @"01/01/2013", @"01/01/2013", @"21/02/2013", @"01/06/2013", @"11/02/2013", @"01/03/2013", @"01/03/2013", @"22/05/2013", @"23/05/2013", @"27/05/2013", @"01/06/2013", @"07/07/2013", @"12/08/2013"]; 

NSCountedSet *set = [[NSCountedSet alloc] initWithArray:yourArray]; 

NSMutableDictionary *dict=[NSMutableDictionary new]; 

for (id obj in set) { 
    [dict setObject:[NSNumber numberWithInteger:[set countForObject:obj]] 
      forKey:obj]; //key is date 
} 

NSLog(@"Dict : %@", dict); 

NSMutableArray *top3=[[NSMutableArray alloc]initWithCapacity:3]; 

//which dict obj is = max 
if (dict.count>=3) { 

    while (top3.count<3) { 
     NSInteger max = [[[dict allValues] valueForKeyPath:@"@max.intValue"] intValue]; 

     for (id obj in set) { 
      if (max == [dict[obj] integerValue]) { 
       NSLog(@"--> %@",obj); 
       [top3 addObject:obj]; 
       [dict removeObjectForKey:obj]; 
      } 
     } 
    } 
} 

NSLog(@"top 3 = %@", top3); 

输出:

2013-11-21 20:50:45.475 Demo[19256:8c03] Dict : { 
    "01/01/2013" = 3; 
    "01/03/2013" = 2; 
    "01/06/2013" = 2; 
    "07/07/2013" = 1; 
    "11/02/2013" = 1; 
    "12/08/2013" = 1; 
    "21/02/2013" = 1; 
    "22/05/2013" = 1; 
    "23/05/2013" = 1; 
    "27/05/2013" = 1; 
} 
2013-11-21 20:50:45.476 Demo[19256:8c03] --> 01/01/2013 
2013-11-21 20:50:45.477 Demo[19256:8c03] --> 01/03/2013 
2013-11-21 20:50:45.477 Demo[19256:8c03] --> 01/06/2013 
2013-11-21 20:50:45.478 Demo[19256:8c03] top 3 = (
    "01/01/2013", 
    "01/03/2013", 
    "01/06/2013" 
)