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 ![]() |
C
CODE #include <stdio.h> #include <string.h> static int matches_pattern_1(const char *s) { struct { unsigned int a; unsigned int b; unsigned int c; } sums = {0,0,0}; while (*s) { switch (*s) { case 'a': sums.a++; break; case 'b': sums.b++; break; case 'c': sums.c++; break; } s++; } return sums.a + sums.b == sums.c; } static int matches_pattern_2(const char *s) { struct { unsigned int a; unsigned int b; unsigned int c; } sums = {0,0,0}; struct { int a; int b; int c; } saw = {0,0,0}; while (*s) { switch (*s) { case 'a': if (saw.b || saw.c) return 0; saw.a = 1; sums.a++; break; case 'b': if (saw.c) return 0; saw.b = 1; sums.b++; break; case 'c': saw.c = 1; sums.c++; break; } s++; } return sums.a + sums.b == sums.c; } static int matches_pattern_3(const char *s) { struct { unsigned int a; unsigned int c; } sums = {0,0}; struct { int a; int b; int c; } saw = {0,0,0}; while (*s) { switch (*s) { case 'a': if (saw.b || saw.c) return 0; saw.a = 1; sums.a++; break; case 'b': if (saw.c) return 0; saw.b = 1; break; case 'c': saw.c = 1; sums.c++; break; } s++; } return sums.a == sums.c && sums.a > 0; } int main(int argc, char **argv) { char buf[81]; while (fscanf(stdin, "%s\n", buf) != EOF) { printf("%s\n", buf); printf(" matches pattern1? %s\n", (matches_pattern_1(buf) ? "true" : "false")); printf(" matches pattern2? %s\n", (matches_pattern_2(buf) ? "true" : "false")); printf(" matches pattern3? %s\n", (matches_pattern_3(buf) ? "true" : "false")); } return 0; } Source: matcher.c |
|
|
![]() ![]() |