Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

[ENTERPRISE] FizzBuzz (part MAXINT) [CODING]

Name: Anonymous 2012-04-08 10:41

Is this ENTERPRISE QUALITY?

#include <stdbool.h>
#include <stdio.h>

struct rule {
  bool (*pred)(int);
  char *word;
};

void count(struct rule rules[], int min, int max) {
  int num, i;
  bool found;

  for (num = min; num <= max; num++) {
    found = false;

    /* search for words */
    for (i = 0; rules[i].pred != NULL; i++) {
      if ((*rules[i].pred)(num)) {
        printf("%s", rules[i].word);
        found = true;
      }
    }

    /* else just print the number */
    if (!found) printf("%d", num);
    putchar('\n');
  }
}

bool Fizz(int x) { return (x % 3 == 0); }
bool Buzz(int x) { return (x % 5 == 0); }

struct rule fizzbuzz_rules[] = {
  {&Fizz, "Fizz"},
  {&Buzz, "Buzz"},
  {NULL, NULL},
};

int main() {
  count(fizzbuzz_rules, 1, 100);
  return 0;
}

Name: Anonymous 2012-04-09 3:52

>>1
Make the action depend on the rule instead.

#include <stdbool.h>
#include <stdio.h>

struct rule {
  bool (*pred)(int);
  void (*action)(int);
};

void apply_range(struct rule rules[], int min, int max) {
  int num, i;

  for (num = min; num <= max; num++) {
    /* apply actions */
    for (i = 0; rules[i].pred != NULL; i++) {
      if ((*rules[i].pred)(num)) {
        (*rules[i].action)(num);
      }
    }
  }
}

bool fizzp(int x) { return (x % 3 == 0); }
void fizza(int x) { printf("Fizz"); }

bool buzzp(int x) { return (x % 5 == 0); }
void buzza(int x) { printf("Buzz");

bool numberp(int x) { return !Fizz(x) && !Buzz(x); }
void numbera(int x) { printf("%d", x); }

bool alwaysp(int x) { return 1; }
void newline(int x) { putchar('\n'); }

struct rule fizzbuzz_rules[] = {
  {fizzp, fizza},
  {buzzp, buzza},
  {numberp, numbera},
  {alwaysp, newline},
  {NULL, NULL},
};

int main() {
  apply_range(fizzbuzz_rules, 1, 100);
  return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List