入力時にハッシュ値でソートして、
出力時に同じハッシュ値のものを表示すればよいのではありませんか?
コード:
#include <stdio.h> // fopen, fclose, fgets, printf
#include <string.h> // strchr
#define WORD_MAX 100
#define WORD_SIZE 256
unsigned int MakeHash1(const char *str, unsigned int hashmax)
{
unsigned int hash = 0;
for (int i = 0; str[i]; i++) hash += str[i];
return hash % hashmax;
}
int main(void)
{
char word[WORD_MAX][WORD_SIZE], *p;
unsigned hash[WORD_MAX];
int index[WORD_MAX], i, j, k, h, n;
FILE *fp = fopen("text.txt", "r");
if (fp == NULL) return printf("ファイルオープンエラー\n"), 1;
for (n = 0; n < WORD_MAX && fgets(word[n], WORD_SIZE, fp); n++) {
if (p = strchr(word[n], '\n')) *p = '\0';
hash[n] = MakeHash1(word[n], 19);
index[n] = n;
for (i = n; i > 0 && hash[index[i-1]] > hash[n]; i--)
index[i] = index[i-1];
index[i] = n;
}
fclose(fp);
if (n) j = 0, h = hash[index[j]];
for (i = 1; i < n; i++) {
k = hash[index[i]];
if (k != h) {
if (j < i-1) {
printf("%s", word[j]);
while (++j < i) printf(", %s", word[j]);
printf(" が %d で衝突\n", h);
}
j = i, h = k;
}
}
}
text.txt
コード:
access
all
american
and
ansi
application
assembly
available
become
been
bell
between
can
code
compiler
compliant
computer
cross
design
designed
despite
efficient
encourage
few
former
general
imperative
implement
includ
institute
instruction
language
level
lexical
low
machine
majority
many
map
memory
microcontroller
mind
minimal
most
national
one
original
platform
prevent
program
provide
purpose
range
require
ritchie
run
scope
see
since
software
source
standardized
standard
static
straightforward
structured
support
system
that
therefore
time
type
typical
unintended
unix
use
variable
variety
various
vendor
very
well
while
wide
実行結果
コード:
access, all, american, and が 0 で衝突
ansi, application が 1 で衝突
assembly, available, become, been, bell, between が 2 で衝突
can, code, compiler, compliant, computer, cross が 3 で衝突
design, designed, despite が 4 で衝突
efficient, encourage, few, former, general, imperative が 5 で衝突
implement, includ, institute が 6 で衝突
instruction, language, level が 7 で衝突
low, machine, majority, many が 9 で衝突
map, memory が 10 で衝突
microcontroller, mind, minimal が 11 で衝突
most, national, one, original, platform, prevent, program, provide が 12 で衝突
purpose, range, require, ritchie, run, scope が 13 で衝突
see, since, software, source, standardized が 14 で衝突
standard, static, straightforward, structured, support が 15 で衝突
system, that が 16 で衝突
therefore, time, type, typical, unintended, unix, use が 17 で衝突
このプログラムが参考になれば、分かりやすいプログラムに書き換えて
提示してください。
質問は何でも受け付けます。