对NSMutuable阵列进行排序/混洗

时间:2010-07-27 15:29:57

标签: objective-c algorithm

我刚刚开始进入Objective-C,我正在尝试对数组进行排序,以使它尽可能地低差异。

int main()
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *myColors;

    myColors = [NSMutableArray arrayWithObjects: @"Red", @"Red",@"Red", @"Red", @"Red", @"Green", @"Green", @"Green", @"Blue", @"Blue", @"Blue", @"Yellow", nil];


    srandom(time(NULL));
    NSUInteger count = [myColors count];
    for (NSUInteger i = 0; i < count; ++i) {
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [myColors exchangeObjectAtIndex:i withObjectAtIndex:n];
         NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);
    }

[pool drain]; return 0;
}

输出类似

的内容
     Element 0 = Blue
     Element 1 = Green
     Element 2 = Yellow
     Element 3 = Blue
     Element 4 = Green
     Element 5 = Red
     Element 6 = Red
     Element 7 = Red
     Element 8 = Blue
     Element 9 = Green
     Element 10 = Red 
     Element 11 = Red

这会对阵列进行洗牌,但由于随机数的原因,它并没有我想要的差异。

理想情况下,每个实例应尽可能远离另一个实例,如:

Red, Green, Red, Blue, Red, Green, Yellow, Red, Blue, Red, Green, Blue

任何帮助和建议都会很棒,我几乎整天都在这里。

4 个答案:

答案 0 :(得分:5)

好吧,我一直坐着试图制作一个洗牌的算法。我认为它做得不错,但可能会有很大改进。它很快就完成了。

我计算每种颜色的频率,并使用它来遍历结果数组。对于结果中的每个对象,我使用频率来确定现在要添加的颜色。有几个if语句可以做到这一点。

这是代码:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *myColors;
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Red",@"Red", @"Red", @"Red", @"Green", @"Green", @"Green", @"Blue", @"Blue", @"Blue", @"Yellow", nil];

NSMutableArray * input = myColors;
NSMutableArray * result = [NSMutableArray arrayWithCapacity:[input count]];

//Start by sorting the array
[input sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO] autorelease]]];

//Calculate the frequency of each color
NSString * lastValue;   
NSMutableArray * calcDict = [NSMutableArray array];
int i=0;
for(NSString * value in myColors){
    if(lastValue != value || i == [input count]-1){
        if(index >= 0){
            double freq = [input count]/[[[calcDict lastObject] valueForKey:@"count"] doubleValue];
            [[calcDict lastObject] setValue:[NSNumber numberWithDouble:freq] forKey:@"freq"];
            [[calcDict lastObject] setValue:[NSNumber numberWithDouble:-freq / 2.0] forKey:@"lastPosition"];
        }

        if(i != [input count]-1){
            [calcDict addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithInt:0],@"count",
                                 value,@"value",nil]];
            lastValue = value;
        }
    }
    [[calcDict lastObject] setValue:[NSNumber numberWithInt:[[[calcDict lastObject] valueForKey:@"count"] intValue]+1] forKey:@"count"];        
    i++;
}

//Sort the calcDict so the one with lowest frequency is first
[calcDict sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"count" ascending:NO] autorelease]]];

//Calculate the result
for(int i=0;i<[input count];i++){
    //Find the color that matches best
    NSDictionary * bestItem = nil;
    for(NSDictionary * dict in calcDict){
        //The distance to where it prefers to be (based on frequency)
        double bestOptimalPositionDistance = ([[bestItem valueForKey:@"freq"]doubleValue]- (i - [[bestItem valueForKey:@"lastPosition"] intValue]) );           

        if(bestItem == nil) //Always use the first item as base since its sorted
            bestItem = dict;
        else {
            if([[bestItem valueForKey:@"lastPosition"] intValue] >= 0){  //If the best item is already added to the result
                double optimalPositionDistance = ([[dict valueForKey:@"freq"]doubleValue] - (i - [[dict valueForKey:@"lastPosition"] intValue]));                   
                if([[dict valueForKey:@"lastPosition"] intValue] < 0){ //if the dict we are looking at is NOT added to the result earlier on
                    if (bestOptimalPositionDistance > 1 || optimalPositionDistance  < 1) { //find out if the dict is more important than the bestItem
                        bestItem = dict;
                    }
                } else if(optimalPositionDistance < bestOptimalPositionDistance){ 
                    bestItem = dict;
                }

            }
        }

    }

    //Add the best item, and update its properties
    [bestItem setValue:[NSNumber numberWithInt:[[bestItem valueForKey:@"count"] intValue]-1] forKey:@"count"];
    [bestItem setValue:[NSNumber numberWithInt:i] forKey:@"lastPosition"];

    [result addObject:[bestItem valueForKey:@"value"]];
    //If there are added enough of the type of color, delete it!
    if([[bestItem valueForKey:@"count"] intValue] <= 0){
        [calcDict removeObject:bestItem];
    }
}

NSLog(@"result: %@",result);

[pool drain]; return 0;

结果是:

Red, Green, Red, Blue, Red, Green, Yellow, Red, Green, Blue, Red, Blue

希望能做到!

答案 1 :(得分:3)

这比它看起来更难......明确的想法是排序唯一值并循环它们(从最高频率值开始)给出了类似的结果:

Red, Green, Blue, Yellow, Red, Green, Blue, Red, Green, Blue, Red, Red

我不确定你的计算“远离另一个”的规则是什么,但我认为答案不是最理想的(例如,如果你交换最后一个Blue,Red对,它会改善)。

闻到NP完全......

答案 2 :(得分:1)

这是一个想法。首先计算每种类型的数量并分成总数。这将告诉你每个应该出现的频率(即每隔一个索引,每三分之一等)。

然后遍历数组,保留每个元素类型的计数器。在每个索引处递增所有计数器,然后检查该索引处的元素类型的计数器是否高于平均分布。如果是,则将其与前一个元素交换,将该类型的计数器归零,然后继续。如果不是继续前进。

这需要多次通过,但最终会有一个均匀分布的列表。我没有完成笔和纸的工作,但这样的事情将是你最好的选择。

修改 - 用笔和纸尝试。如果你开始排序,它可能需要尽可能多的传递,因为你有元素。如果先进行随机化,并且每种元素的数量相似,则需要的时间要少得多。这只是挥舞着手臂......

答案 3 :(得分:1)

另一个想法:

首先列出每个不同的值,即:

Red, Red, Red, Red, Red
Green, Green, Green
Blue, Blue, Blue
Yellow

然后将它们合并到一个列表中,从最大列表开始,以便在每个第i个位置添加一个新元素。记住最后一个插入点,以便填写整个列表,而不仅仅是David Gelhar的回答。如果你到达目的地,我会增加:

Red, Red, Red, Red, Red // i = 1
Red, Green, Red, Green, Red, Green, Red, Red // i = 2
Red, Green, Red, Green, Red, Green, Red, Blue, Red // wrap-around, increment i
Red, Green, Blue, Red, Green, Blue, Red, Green, Red, Blue, Red // i = 3 
Red, Green, Blue, Red, Green, Blue, Red, Green, Yellow, Red, Blue, Red // i = 3

我认为这不会产生最佳解决方案,但它可能足以满足您的目的。