Seems like you can use NSSet as key to NSDictionary:
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];
set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];
id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
NSLog(@"%@ : %@", key, [dict objectForKey:key]);
set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);
Outputs:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2
Another way is to use NSMutableDictionary
that holds multiple NSSet
's of items and price as a key, however is noted this will not work if the price is not unique.
You check manually if the set is in dictionary by iterating over items and for each set using isEqualToSet:
- unless anyone can come up with better way.
If it is you return the price (key) if it is not you can insert it with a price, the main parts:
@interface ShoppingList : NSObject
{
NSMutableDictionary * shoppingList;
}
- (void)setList:(NSSet*)aList
forPrice:(double)aPrice
{
[shoppingList setObject:aList forKey:[NSNumber numberWithDouble:aPrice]];
}
- (double)priceForList:(NSSet*)aList
{
id key;
NSEnumerator * enumerator = [shoppingList keyEnumerator];
while ((key = [enumerator nextObject]))
{
NSSet * list = [shoppingList objectForKey:key];
if ([aList isEqualToSet:list])
{
return [(NSNumber*)key doubleValue];
}
}
return 0.0;
}
{
ShoppingList * shoppingList = [[ShoppingList alloc] init];
NSSet * list;
double price = 0.0;
list =
[NSSet setWithObjects:@"apple",@"green_apple",@"pineapple",nil];
[shoppingList setList:list forPrice:9.99];
list =
[NSSet setWithObjects:@"grapes",@"banana",@"strawberries",@"apple",nil];
[shoppingList setList:list forPrice:15.99];
list =
[NSSet setWithObjects:@"orange",@"grapes",@"green_apple",nil];
[shoppingList setList:list forPrice:7.50];
// searching for this
list =
[NSSet setWithObjects:@"grapes",@"banana",@"strawberries",@"apple",nil];
price = [shoppingList priceForList:list];
if (price != 0.0)
{
NSLog(@"price: %.2f, for pricelist: %@", price, list);
}
else
{
NSLog(@"shopping list not found: %@", list);
[shoppingList setList:list forPrice:15.99];
}
}