Big Fish Interview Question
iOS DevelopersCountry: United States
Interview Type: In-Person
NSString *input = @"johndoe_sdfjkldfj_ldfjlkfdsjfds_dfdjklfdsjs.txt";
input = [input substringToIndex:input.length-4];
NSArray *components = [input componentsSeparatedByString:@"_"];
NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:components.count];
if (components.count>0) {
NSString *name = components[0];
result[@"NAME"]=name;
for (int i = 1; i<components.count; i++) {
NSString *component = components[i];
NSString *key = [component substringToIndex:1];
NSString *value = [component substringFromIndex:1];
result[key]=value;
}
}
NSLog(@"%@", result);
If duplicate token, I will not use the token as the key, I will use index as the key. Then make another mapping from index to token.
This is my shot with Objective-C. It's probably not the most elegant solution but it seems to work.
NSString *test = @"johndoe_sdfjkldfj_ldfjlkfdsjfds_dfdjklfdsjs.txt";
NSString *regexString = @"\\.(...)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:nil];
test = [regex stringByReplacingMatchesInString:test options:0 range:NSMakeRange(0, [test length]) withTemplate:@""];
NSMutableArray *testArray = [[NSMutableArray alloc]init];
[testArray addObjectsFromArray:[test componentsSeparatedByString:@"_"]];
NSMutableDictionary *testDict = [[NSMutableDictionary alloc]init];
[testDict addEntriesFromDictionary:@{@"NAME":testArray[0]}];
[testArray removeObjectAtIndex:0];
for (NSString *string in testArray) {
NSMutableString *mutString = [string mutableCopy];
NSString *key = [mutString substringToIndex:1];
[mutString deleteCharactersInRange:NSMakeRange(0, 1)];
[testDict addEntriesFromDictionary:@{key:mutString}];
}
NSLog(@"%@", testDict);
I chose to map from the key to a list of ordered values (for collisions):
Output is:
This solution handles all of the corner cases I could think of:
- caleb.cittadino April 24, 20141) Null fileName
2) Empty fileName
3) fileName with missing extension
4) fileName with no underscores
5) fileName with underscores, without key-value-pairs
6) fileName with underscores, with 1 or more key-emptyValue-pairs
What do you guys think? Any better way to parse this? Any corner cases I missed?