Select Page

Well I can’t leave this alone. Here’s a ‘C’ version:


#include <stdio.h>
#include <string.h>
#include <malloc.h>
char *words[] = {
  "tsar", "rat", "tar", "star",
  "tars", "cheese", "mow", "lox",
  NULL
};
#define LETTERS 26
// the following assumes the alphabet is no more than 256 symbols
static char hashcount[LETTERS];
// the following assumes a word's symbols never repeats more than 256
static char hashbuffer[LETTERS*3+1];
char *hash(char *word) {
  char *ptr = word;
  int i;
  for (i=0; i<LETTERS; i++) hashcount[i] = 0;
  while (*ptr) {
    char c = tolower(*ptr);
    if (c >= 'a' && c <= 'z') hashcount[c-'a']++;
    ptr++;
  }
  ptr = hashbuffer;
  for (i=0; i<LETTERS; i++) {
    if (hashcount[i]) {
      *ptr++ = i + 'a';
      if (hashcount[i] > 1) {
        sprintf(ptr, "%x", hashcount[i]);
        ptr += (hashcount[i]/16 + 1);
      }
    }
  }
  *ptr = '\0';
  return strdup(hashbuffer);
}
int main(int argc, char *argv[]) {
  char **id = NULL;
  char *printed = NULL;
  int i, j, len=0;
  while (1) {
    if (words[len] == NULL) break;
    len++;
  }
  id = (char **)malloc(len*sizeof(char *));
  printed = (char *)malloc(len*sizeof(char));
  for (i=0; i<len; i++) {
    id[i] = hash(words[i]);
    printed[i] = 0;
    printf("[%d] %s : %s\n", i, words[i], id[i]);
  }
  for (i=0; i<len; i++) {
    if (printed[i] == 0) {
      printed[i] = 1;
      printf("===\n");
      printf("%s\n", words[i]);
      for (j=i+1; j<len; j++) {
        if (printed[j] == 0 && (strcmp(id[i], id[j]) == 0)) {
          printed[j] = 1;
          printf("%s\n", words[j]);
        }
      }
    }
  }
  for (i=0; i<len; i++) free(id[i]);
  free(id);
  free(printed);
  return 0;
}

…and its output:


[0] tsar : arst
[1] rat : art
[2] tar : art
[3] star : arst
[4] tars : arst
[5] cheese : ce3hs
[6] mow : mow
[7] lox : lox
===
tsar
star
tars
===
rat
tar
===
cheese
===
mow
===
lox