Skip to content

Instantly share code, notes, and snippets.

@iamleeg
Created February 16, 2021 21:31
Show Gist options
  • Save iamleeg/27dfc3900752ed84d7e7d1cb4e8ce268 to your computer and use it in GitHub Desktop.
Save iamleeg/27dfc3900752ed84d7e7d1cb4e8ce268 to your computer and use it in GitHub Desktop.
FizzBuzz in Objective-C
// hey, we've all got a coding interview to crack, right?
#import <Foundation/Foundation.h>
@interface FZBZSparseArray : NSArray
- initWithCount:(NSUInteger)count placeholder:placeholder overrides:overrides;
@end
@interface FZBZWrappedArray : NSArray
- initWrappingArray:underlyingArray;
@end
@interface NSMutableDictionary (Every)
- (void)every:(NSUInteger)skip from:(NSUInteger)min upTo:(NSUInteger)max is:anObject;
@end
@interface NSNumber (FizzBuzz)
- fizzBuzzValue;
@end
@implementation NSNumber (FizzBuzz)
- fizz { return @"Fizz"; }
- buzz { return @"Buzz"; }
- fizzBuzz { return @"FizzBuzz"; }
- fizzBuzzValue
{
static id selectors = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
id overrides = [NSMutableDictionary dictionary];
[overrides every:3 from:3 upTo:13 is:@"fizz"];
[overrides every:5 from:5 upTo:11 is:@"buzz"];
overrides[@0] = @"fizzBuzz";
id selectorMap = [[FZBZSparseArray alloc]
initWithCount:15
placeholder:@"stringValue"
overrides:overrides];
selectors = [[FZBZWrappedArray alloc] initWrappingArray:selectorMap];
});
return [self performSelector:
NSSelectorFromString(selectors[[self unsignedIntegerValue]])];
}
@end
@implementation NSMutableDictionary (Every)
- (void)every:(NSUInteger)skip from:(NSUInteger)min upTo:(NSUInteger)max is:anObject
{
for (NSUInteger i = min; i < max; i += skip)
{
self[@(i)] = anObject;
}
}
@end
@implementation FZBZWrappedArray
{
id _array;
}
- initWrappingArray:underlyingArray
{
self = [super init];
if (self)
{
_array = [underlyingArray copy];
}
return self;
}
- (NSUInteger)count { return NSUIntegerMax; }
- objectAtIndex:(NSUInteger)index
{
return _array[index % [_array count]];
}
@end
@implementation FZBZSparseArray
{
id _placeholder;
id _knownValues;
NSUInteger _count;
}
- initWithCount:(NSUInteger)count placeholder:placeholder overrides:overrides
{
self = [super init];
if (self)
{
_placeholder = placeholder;
_knownValues = [overrides copy];
_count = count;
}
return self;
}
- objectAtIndex:(NSUInteger)index
{
return _knownValues[@(index)] ? _knownValues[@(index)] : _placeholder;
}
- (NSUInteger)count { return _count; }
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
for (NSUInteger i = 1; i < 51; i++)
{
printf("%s\n", [[@(i) fizzBuzzValue] UTF8String]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment