Showing posts with label NSCountedSet. Show all posts
Showing posts with label NSCountedSet. Show all posts

Sunday, June 16, 2013

NSCountedSet initWithCapacity example in Objective C (iOS).


NSCountedSet initWithCapacity

Returns a counted set object initialized with enough memory to hold a given number of objects.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the new counted set.

Return Value
A counted set object initialized with enough memory to hold numItems objects

Discussion of [NSCountedSet initWithCapacity]
The method is the designated initializer for NSCountedSet.

Note that the capacity is simply a hint to help initial memory allocation—the initial count of the object is 0, and the set still grows and shrinks as you add and remove objects. The hint is typically useful if the set will become large.

NSCountedSet initWithCapacity example.
NSDictionary * dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:2], @"bar", nil];
NSDictionary * dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:3], @"bar", nil];
NSDictionary * dict3 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:2], @"foo",
                        [NSNumber numberWithInt:1], @"bar", nil];
NSArray * arrayOfDictionaries = [[NSArray alloc] initWithObjects:
                                 dict1, dict2, dict3, nil];

// count all keys in an array of dictionaries (arrayOfDictionaries):

NSMutableDictionary * countKeys = [[NSMutableDictionary alloc] initWithCapacity:0];
NSCountedSet * counts = [[NSCountedSet alloc] initWithCapacity:0];

NSArray * keys;
NSString * pairString;
NSString * countKey;
for (NSDictionary * dictionary in arrayOfDictionaries)
{
    keys = [dictionary allKeys];
    for (NSString * key in keys)
    {
        pairString = [NSString stringWithFormat:@"%@->%@", key, [dictionary valueForKey:key]];
        if ([countKeys valueForKey:pairString] == nil)
        {
            [countKeys setValue:[NSString stringWithString:pairString] forKey:pairString];
        }
        countKey = [countKeys valueForKey:pairString];
        { [counts addObject:countKey]; }
    }
}

NSLog(@"%@", counts);

[counts release];
[countKeys release];

[arrayOfDictionaries release];
[dict1 release];
[dict2 release];
[dict3 release];

Example of [NSCountedSet initWithCapacity].
UIImage        *image;
int             randomIndex;

NSCountedSet   *set    = [[NSCountedSet alloc] initWithCapacity:50];
NSMutableArray *arrays = [[NSMutableArray alloc] initWithCapacity:5];

for ( int i = 0; i < 5; i++ ) {
    while ( [set count] < 50 ) {
        randomIndex = arc4random() % 6;
        image = [images objectAtIndex:randomIndex];

        switch ( [set count] ) {
            case 48:
            case 49:
                if ( [set countForObject:image] < 9 ) {
                    [set addObject:image];
                }
                break;

            default:
                if ( [set countForObject:image] < 8 ) {
                    [set addObject:image];
                }
        }
    }

    [arrays addObject:[set allObjects]];
    [set removeAllObjects];
}

[set release];

NSCountedSet initWithCapacity example.
@implementation NSString(permutation)
- (BOOL)isPermutation:(NSString*)other
{
    if( [self length] != [other length] ) return NO;
    if( [self isEqualToString:other] )    return YES;
    NSUInteger length = [self length];
    NSCountedSet* set1 = [[[NSCountedSet alloc] initWithCapacity:length] autorelease];
    NSCountedSet* set2 = [[[NSCountedSet alloc] initWithCapacity:length] autorelease];
    for( int i = 0; i < length; i++ ) {
        NSRange range = NSMakeRange(i, 1);
        [set1 addObject:[self substringWithRange:range]];
        [set2 addObject:[self substringWithRange:range]];
    }
    return [set1 isEqualTo:set2];
}
@end

End of NSCountedSet initWithCapacity example article.

NSCountedSet initWithArray example in Objective C (iOS).


NSCountedSet initWithArray

Returns a counted set object initialized with the contents of a given array.

- (id)initWithArray:(NSArray *)anArray

Parameters
anArray
An array of objects to add to the new set.

Return Value of [NSCountedSet initWithArray]
An initialized counted set object with the contents of anArray. The returned object might be different than the original receiver.

NSCountedSet initWithArray example.
- (void)testOccurrenceCounting
{
    NSArray *numbers = @[@1, @3, @4, @6, @6, @3, @1, @3];
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:numbers];
    NSMutableArray *counters = [NSMutableArray arrayWithCapacity:[set count]];
    [set enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        [counters addObject:[[Pair alloc] initWithKey:obj value:@([set countForObject:obj])]];
    }];
    [counters sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES]]];

    NSLog(@"%@", counters);
}

Example of [NSCountedSet initWithArray].
NSMutableArray *array = …;
NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
    autorelease];

// Array with distinct elements only, sorted by their repeat count
NSArray *distinctArray = [[countedSet allObjects]
    sortedArrayUsingFunction:countedSort context:countedSet];

// Array with all the elements, where elements representing the same
// object are contiguous
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in distinctArray) {
    for (NSUInteger i = 0; i < [countedSet countForObject:object]; i++) {
        [sortedArray addObject:object];
    }
}

NSCountedSet initWithArray example.
countedList = [[NSCountedSet alloc] initWithArray:listOfItems];//listOfItems is an array of country name strings with duplicates
    listOfItems2 = [NSMutableArray array]; // array without duplicates that's the data source for the UITableView

    for (NSString *aCountry in countedList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:aCountry forKey:@"name"];
        [dict setValue:[NSString stringWithFormat:@"%lu",[countedList countForObject:aCountry]] forKey:@"count"];
        [listOfItems2 addObject:dict];
    }

End of NSCountedSet initWithArray example article.

NSCountedSet countForObject example in Objective C (iOS).


NSCountedSet countForObject

Returns the count associated with a given object in the set.

- (NSUInteger)countForObject:(id)anObject

Parameters
anObject
The object for which to return the count.

Return Value of [NSCountedSet countForObject]
The count associated with anObject in the set, which can be thought of as the number of occurrences of anObject present in the set.

NSCountedSet countForObject example.
The sample below ...

    NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
    NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];

    for (id item in set)
    {
        NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
    }

Example of [NSCountedSet countForObject].
countedList = [[NSCountedSet alloc] initWithArray:listOfItems];//listOfItems is an array of country name strings with duplicates
    listOfItems2 = [NSMutableArray array]; // array without duplicates that's the data source for the UITableView

    for (NSString *aCountry in countedList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:aCountry forKey:@"name"];
        [dict setValue:[NSString stringWithFormat:@"%lu",[countedList countForObject:aCountry]] forKey:@"count"];
        [listOfItems2 addObject:dict];
    }

NSCountedSet countForObject example.
    NSArray *arr = @[@1, @3, @4, @6, @6, @3, @1, @3];
    NSCountedSet *totalSet = [NSCountedSet setWithArray:arr];
    NSMutableArray *dictArray = [NSMutableArray array];
    for (NSNumber *num in totalSet) {
        NSDictionary *dict = @{@"number":num, @"count":@([totalSet countForObject:num])};
        [dictArray addObject:dict];
    }
    NSArray *final = [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES ]]];
    NSLog(@"%@",final);

End of NSCountedSet countForObject example article.

NSCountedSet addObject example in Objective C (iOS).


NSCountedSet addObject

Adds a given object to the set.

- (void)addObject:(id)anObject

Parameters
anObject
The object to add to the set.

Discussion of [NSCountedSet addObject]
If anObject is already a member, addObject: increments the count associated with the object. If anObject is not already a member, it is sent a retain message.

NSCountedSet addObject example.
countedList = [[NSCountedSet alloc] initWithArray:listOfItems];//listOfItems is an array of country name strings with duplicates
    listOfItems2 = [NSMutableArray array]; // array without duplicates that's the data source for the UITableView

    for (NSString *aCountry in countedList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:aCountry forKey:@"name"];
        [dict setValue:[NSString stringWithFormat:@"%lu",[countedList countForObject:aCountry]] forKey:@"count"];
        [listOfItems2 addObject:dict];
    }

Example of [NSCountedSet addObject].
    NSArray *arr = @[@1, @3, @4, @6, @6, @3, @1, @3];
    NSCountedSet *totalSet = [NSCountedSet setWithArray:arr];
    NSMutableArray *dictArray = [NSMutableArray array];
    for (NSNumber *num in totalSet) {
        NSDictionary *dict = @{@"number":num, @"count":@([totalSet countForObject:num])};
        [dictArray addObject:dict];
    }
    NSArray *final = [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES ]]];
    NSLog(@"%@",final);

NSCountedSet addObject example.
@interface NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count;

@end

@implementation NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count {
   NSMutableArray *array = [NSMutableArray array];
   for(id obj in self) {
      if([self countForObject:obj] == count) {
        [array addObject:obj];
      } 
   }
   return [array copy];
}

@end

End of NSCountedSet addObject example article.