Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 963291
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T01:38:57+00:00 2026-05-16T01:38:57+00:00

Im just starting getting into Objective-C, i’m trying to sort an array so it

  • 0

Im just starting getting into Objective-C, i’m trying to sort an array so it is as low discrepancy as possible.

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

Which outputs something like

     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

Which shuffles the array, but it isn’t as low discrepancy as I would like due to random number.

Ideally each instance should be as far away from another one of it’s kind as possible like:

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

Any help and suggestions would be greats, I’ve been going at this pretty much all day.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T01:38:58+00:00Added an answer on May 16, 2026 at 1:38 am

    Okay, i’ve been sitting and trying to make an algorithme that shuffles an array. I think it does a decent job, but can probably be improved a lot. Its done quickly.

    I calculate the frequency of each color, and use that for traversing the result array. For each object in the result i use the frequency to determine what color to add now. There are several if statements to do that.

    This is the code:

    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;
    

    The result of this is:

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

    Hope that does it!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Getting thrown into ColdFusion dev at work and just starting out, I wonder if
Just starting android development and trying to create a UI here.. but getting the
I'm just starting to get into C++ (I'm an experienced Python/Java developer getting into
Just starting getting into Entity Framework and Linq for EF. I'm not sure which
I'm just starting getting into Python - my focus being on using it with
I'm just starting out with learning Java, and have run into a problem. When
I am new to unit testing, just getting into it using Check for C.
I'm getting this error when trying to insert data from a form into a
I want to pass a struct array into a function and I keep getting
Just trying to learn C++. I'm starting off with a scraper. The idea is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.