Program this!, Programming thread |
Program this!, Programming thread |
![]()
Post
#1
|
|
![]() Senior Member ![]() ![]() ![]() ![]() ![]() ![]() Group: Administrator Posts: 2,648 Joined: Apr 2008 Member No: 639,265 ![]() |
I'm of the understand that there are a few Technology forum aficionados that are programmers, or are at least interested in programming, so I thought I'd start a thread -- a sort of game. The game was inspired by this thread. It's pretty simple: just implement the following program in whatever language you desire. If someone's already posted a program in your favorite language, see if you can do better! You get bragging rights if you implement the program in a weird/unusual/rare language.
Here are the guidelines for the program:
|
|
|
![]() |
![]()
Post
#2
|
|
![]() Senior Member ![]() ![]() ![]() ![]() ![]() ![]() Group: Administrator Posts: 2,648 Joined: Apr 2008 Member No: 639,265 ![]() |
Objective-C
This one isn't dramatically different from the C version...but for such a low-level task, that's to be expected, I guess. CODE /* Compile: * $ gcc -std=c99 -o matcher-objc -framework Foundation matcher.m * # ./matcher-objc */ #import <Foundation/Foundation.h> #define foreach(s) for (unsigned int i = 0; i < [s length]; i++) static BOOL matchesPattern1(NSString *s) { struct { unsigned int a; unsigned int b; unsigned int c; } sums = {0,0,0}; foreach(s) { switch ([s characterAtIndex:i]) { case 'a': sums.a++; break; case 'b': sums.b++; break; case 'c': sums.c++; break; } } return sums.a + sums.b == sums.c; } static BOOL matchesPattern2(NSString *s) { struct { unsigned int a; unsigned int b; unsigned int c; } sums = {0,0,0}; struct { BOOL a; BOOL b; BOOL c; } saw = {NO,NO,NO}; foreach(s) { switch ([s characterAtIndex:i]) { case 'a': if (saw.a || saw.b) return NO; saw.a = YES; sums.a++; break; case 'b': if (saw.c) return NO; saw.b = YES; sums.b++; break; case 'c': saw.c = YES; sums.c++; break; } } return sums.a + sums.b == sums.c; } static BOOL matchesPattern3(NSString *s) { struct { unsigned int a; unsigned int c; } sums = {0,0}; struct { BOOL a; BOOL b; BOOL c; } saw = {NO,NO,NO}; foreach(s) { switch ([s characterAtIndex:i]) { case 'a': if (saw.b || saw.c) return NO; saw.a = YES; sums.a++; break; case 'b': if (saw.c) return NO; saw.b = YES; break; case 'c': saw.c = YES; sums.c++; break; } } return sums.a == sums.c && sums.a > 0; } int main(int argc, char **argv) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; char buf[81]; while (fscanf(stdin, "%s\n", buf) != EOF) { NSString *s = [[NSString alloc] initWithCString:buf]; printf("%s\n", [s UTF8String]); printf(" matches pattern 1? %s\n", (matchesPattern1(s) ? "true" : "false")); printf(" matches pattern 2? %s\n", (matchesPattern2(s) ? "true" : "false")); printf(" matches pattern 3? %s\n", (matchesPattern3(s) ? "true" : "false")); [s release]; } [pool release]; return 0; } Source: matcher.m |
|
|
![]() ![]() |