【问题标题】:Sort array with a count value使用计数值对数组进行排序
【发布时间】:2012-11-03 09:36:44
【问题描述】:

我有一个包含一些字符串的数组。为字符串的每个字符分配一个整数值。例如 a=2,b=5,c=6 ,o=1,k=3 等

a 字符串中的最终值是字符值的总和。因此,对于示例字符串“BOOK”,该字符串将存储为“BOOK (7)”。同样,每个字符串都有一个最终的整数值。我想用存储在每个数组索引中的字符串中的这些最终整数值对这些数组进行排序。该数组包含超过 200,000 个单词。所以排序过程应该很快。有什么方法吗?

【问题讨论】:

  • 我认为你应该对整数部分使用正则表达式,然后你可以对数据进行排序
  • 在这种情况下如何使用正则表达式?
  • 你的数组是这样的:["book5", "table3", "pen2"]?
  • 据我所知,他的数组类似于 ["BOOK (7)", "Table (3)", "Pen (2)"]。
  • 当你想稍后使用它进行排序时将总和放入字符串中不是很实用。改变它,你的问题就会消失。

标签: iphone ios ios5 ios4 ios6


【解决方案1】:

一个简单的例子可能是,如果你的字符串结构总是相同的,比如“Book (7)”,你可以通过找到“()”之间的数字来对字符串进行操作,然后你可以使用字典来暂时存储对象:

    NSMutableArray *arr=[NSMutableArray arrayWithObjects:@"Book (99)",@"Pencil (66)",@"Trash (04)", nil];
    NSLog(@"%@",arr);

    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    //Find the numbers and store each element in the dictionary 
    for (int i =0;i<arr.count;i++) {
        NSString *s=[arr objectAtIndex:i];
        int start=[s rangeOfString:@"("].location;
        NSString *sub1=[s substringFromIndex:start];
        NSString *temp1=[sub1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
        NSString *newIndex=[temp1 stringByReplacingOccurrencesOfString:@")" withString:@""];
        //NSLog(@"%d",[newIndex intValue]);
        [dict setValue:s forKey:newIndex];
    }
    //Sorting the keys and create the new array
    NSArray *sortedValues = [[dict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSMutableArray *newArray=[[NSMutableArray alloc]init];
    for(NSString *valor in sortedValues){
               [newArray addObject:[dict valueForKey:valor]];
        }
    NSLog(@"%@",newArray);

打印出来:

(
《书(99)》,
“铅笔 (66)”,
《垃圾(04)》
)

(
“垃圾(04)”,
“铅笔 (66)”,
《书(99)》
)

【讨论】:

  • 感谢 Mat 帮助很大,非常感谢您的支持和时间
【解决方案2】:

据我了解,您想对包含以下格式的字符串的数组进行排序

a=3

并且您想在忽略字符的情况下根据数字进行排序。 在这种情况下,以下代码将适用于您

-(NSArray *)Sort:(NSArray*)myArray
{
    return [myArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
            {
                NSString *first = [[obj1 componentsSeparatedByString:@"="] objectAtIndex:1];
                NSString *second = [[obj2 componentsSeparatedByString:@"="] objectAtIndex:1];
                return [first caseInsensitiveCompare:second];
            }];
}

如何使用:

NSArray *arr= [[NSArray alloc] initWithObjects:@"a=3",@"b=1",@"c=4",@"f=2", nil];
NSArray *sorted = [self Sort:arr];

for (NSString* str in sorted)
{
    NSLog(@"%@",str);
}

输出

b=1
f=2
a=3
c=4

【讨论】:

    【解决方案3】:

    试试这个方法

    +(NSString*)strTotalCount:(NSString*)str
    {
       NSInteger totalCount =  0;
       // initial your character-count directory
       NSDictionary* characterDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:2], [NSString stringWithUTF8String:"a"],
        [NSNumber numberWithInt:5], [NSString stringWithUTF8String:"b"],
        [NSNumber numberWithInt:6], [NSString stringWithUTF8String:"c"],
        [NSNumber numberWithInt:1], [NSString stringWithUTF8String:"o"],
        [NSNumber numberWithInt:3], [NSString stringWithUTF8String:"k"],
                                       nil];
    
       NSString* tempString = str;
      for (NSInteger i =0; i<tempString.length; i++) {
        NSString* character  = [tempString substringWithRange:NSMakeRange(i, 1)];
        character = [character lowercaseString];
        NSNumber* count = [characterDictionary objectForKey:character];
        totalCount += [count integerValue];
      };
      return [NSString stringWithFormat:@"%@(%d)",str,totalCount];
    }
    

    测试句:

     NSLog(@"%@", [ViewController strTotalCount:@"BOOK"]);
    

    将输出“BOOK(10)”

    您可以将 ViewController 更改为您自己的类名;

    【讨论】:

    • 这真的让我发笑。你抽了什么?
    【解决方案4】:

    首先 - 创建一个自定义对象来保存您的值。不要将值放在字符串中。 排序不是你的基本问题。问题是您将值保存到难以提取的字符串中。

    @interface StringWithValue
    
    @property (nonatomic, copy, readwrite) NSString* text;
    @property (nonatomic, assign, readwrite) NSUInteger value;
    
    - (id)initWithText:(NSString*)text;
    
    - (NSComparisonResult)compare:(StringWithValue*)anotherString;
    
    @end
    
    @implementation StringWithValue
    
    @synthesize text = _text;
    @synthesize value = _value;
    
    - (id)initWithText:(NSString*)text {
        self = [super init];
    
        if (!self) {
           return nil;
        }
    
        self.text = text;
        self.value = [self calculateValueForText:text];
    
        return self;
    }
    
    - (NSComparisonResult)compare:(StringWithValue*)anotherString {
       if (self.value  anotherString.value) {
          return NSOrderedDescending;
       }
       else {
          return NSOrderedSame;
       }
    }
    
    - (NSString*)description {
        return [NSString stringWithFormat:@"%@ (%u)", self.text, self.value];
    }
    
    @end
    

    然后对数组进行排序将是sortUsingSelector: 的简单用法。 请注意,这将在性能上击败所有其他答案,因为无需在每次比较时解析值。

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2011-03-17
      相关资源
      最近更新 更多