简体   繁体   English

用计数值对数组排序

[英]Sort array with a count value

I have an array which contains some strings. 我有一个包含一些字符串的数组。 For each character of a string an integer value is assigned. 为字符串的每个字符分配一个整数值。 For example a=2,b=5,c=6 ,o=1,k=3 etc 例如a = 2,b = 5,c = 6,o = 1,k = 3等

The final value in the a string is the sum of the character's value. 字符串中的最终值是字符值的总和。 So that for an example string "BOOK" the string will be stored as "BOOK (7)". 这样,对于示例字符串“ BOOK”,该字符串将存储为“ BOOK(7)”。 Similarly every string will have a final integer value. 同样,每个字符串都有一个最终的整数值。 I would like to sort these array with these final integer values stored in the string which is present in each array index. 我想用存储在每个数组索引中的字符串中的这些最终整数值对这些数组进行排序。 The array contains more than 200,000 words. 该数组包含超过200,000个单词。 So the sorting process should be pretty fast. 因此,排序过程应该非常快。 Is there any method for it? 有什么办法吗?

A brutal quick example could be, if your strings structure is always the same, like "Book (7)" you can operate on the string by finding the number between the "()" and then you can use a dictionary to store temporally the objects: 一个简短的残酷示例是,如果您的字符串结构始终相同,例如“ 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);

This prints: 打印:

(
"Book (99)", “书(99)”,
"Pencil (66)", “铅笔(66)”,
"Trash (04)" “垃圾(04)”
)

(
"Trash (04)", “垃圾(04)”,
"Pencil (66)", “铅笔(66)”,
"Book (99)" “书(99)”
)

as i understand, you want to sort an array which contains string formated in the following 据我了解,您想对包含以下格式的字符串的数组进行排序

a=3

and you want to sort according to the number while ignoring the character. 并且您想在忽略字符的同时根据数字进行排序。 in this case the following code will work with you 在这种情况下,以下代码将与您一起工作

-(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];
            }];
}

How to use it: 如何使用它:

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);
}

Output 产量

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

Try this methods 试试这个方法

+(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];
}

The test sentence: 测试语句:

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

will output " BOOK(10) " 将输出“ BOOK(10)”

You may change the ViewController to you own class name; 您可以将ViewController更改为自己的类名;

First - create a custom object to save your values. 首先-创建一个自定义对象以保存您的值。 Don't put the value inside the string. 不要将值放在字符串中。 Sorting is not your base problem. 排序不是您的基本问题。 The problem is that you are saving values into a string from where they are difficult to extract. 问题是您要将值保存到难以提取的字符串中。

@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

Sorting the array then would be a simple use of sortUsingSelector: . 然后,对数组进行排序将是sortUsingSelector:的简单使用。 Note this will beat all other answers in performance as there is no need to parse the value with every comparison. 请注意,这将消除性能上的所有其他答案,因为无需每次比较都解析该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM