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

/prog/ challenge

Name: Anonymous 2012-12-24 0:12

All right, /prog/, it is time for the ultimate challenge. Your task, if you are EXPERT to accept it, it to program something of reasonable complexity, in the language of your choice, how ever you see fit. In one year, you will reevaluate your code and comment on your design choices. Can you write code that will stand the test of time?

Name: Lambda Arthur Wordcounterless 2012-12-24 8:10

I ACCEPT!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
    char *str;
    int val;
    struct node *next;
};

static struct node *tab[2048];

static unsigned int hash(const char *str)
{
    enum { MULTIPLIER = 31 };
    unsigned int h = 0;

    while (*str)
        h = MULTIPLIER * h + (unsigned char) *str++;
    return h % (sizeof tab / sizeof tab[0]);
}

static struct node *install(struct node *np)
{
    unsigned int h;

    np->next = tab[(h = hash(np->str))];
    tab[h] = np;
    return np;
}

static struct node *lookup(const char *str)
{
    struct node *np;

    for (np = tab[hash(str)]; np && strcmp(str, np->str); np = np->next)
        ;
    return np;
}

static struct node *new(const char *str)
{
    struct node *v;

    if (!(v = malloc(sizeof *v)) || !(v->str = malloc(strlen(str) + 1)))
        exit(EXIT_FAILURE);
    strcpy(v->str, str);
    v->val = 1;
    return v;
}

static void print(struct node *const *tab, size_t n)
{
    struct node *tp;

    while (n--)
        for (tp = *tab++; tp; tp = tp->next)
            printf("%d %s\n", tp->val, tp->str);
}

int main(void)
{
    struct node *ptr;
    char buf[2048];

    while (scanf("%2047s", buf) == 1)
        if (!(ptr = lookup(buf)))
            install(new(buf));
        else
            ptr->val++;
    print(tab, sizeof tab / sizeof tab[0]);
    return 0;
}

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