Problem 94: Hamming Codes
Hamming Codes
Rob Kolstad
Given N, B, and D: Find a set of N codewords (1 <= N <= 64), each of
length B bits (1 <= B <= 8), such that each of the codewords is at least
Hamming distance of D (1 <= D <= 7) away from each of the other codewords.
The Hamming distance between a pair of codewords is the number of binary bits
that differ in their binary notation. Consider the two codewords 0x554 and 0x234
and their differences (0x554 means the hexadecimal number with hex digits 5, 5,
and 4):
0x554 = 0101 0101 0100
0x234 = 0010 0011 0100
Bit differences: xxx xx
Since five bits were different, the Hamming distance is 5.
PROGRAM NAME: hamming
INPUT FORMAT
N, B, D on a single line
SAMPLE INPUT (file hamming.in)
16 7 3
OUTPUT FORMAT
N codewords, sorted, in decimal, ten per line. In the case of multiple
solutions, your program should output the solution which, if interpreted as a
base 2^B integer, would have the least value.
SAMPLE OUTPUT (file hamming.out)
0 7 25 30 42 45 51 52 75 76
82 85 97 102 120 127
題目要求:
求出N個(gè)數(shù),是這些數(shù)種任意兩個(gè)的漢明碼>= D。(漢明碼:兩個(gè)數(shù)的二進(jìn)制相同位上不同數(shù)字的個(gè)數(shù))
代碼如下:
/*
LANG: C
TASK: hamming
*/
#include<stdio.h>
int len, n, b, d, path[100], largest;
int Dis(int x)
{
int z, num, i;
for (i = 0; i < len; i++)
{
//對兩個(gè)數(shù)字異或,得出的數(shù)的二進(jìn)制含1的個(gè)數(shù)就是原來兩個(gè)數(shù)在二進(jìn)制下相同位上不同數(shù)字的個(gè)數(shù)
z = x ^ path[i];
num = 0;//計(jì)算個(gè)數(shù)
while (z)//求兩個(gè)數(shù)的二進(jìn)制對應(yīng)位上不同數(shù)字的個(gè)數(shù)
{
z &= z - 1;
num++;
}
if (num < d)
{
return 0;
}
}
return 1;
}
void Dfs(int th)
{
if (len == n)
{
return;
}
int i, cost;
for (i = th + 1; i < largest; i++)
{
if (Dis(i))
{
path[len++] = i;
Dfs(i);
break;
}
}
}
int main()
{
freopen("hamming.in", "r", stdin);
freopen("hamming.out", "w", stdout);
int i;
scanf("%d%d%d", &n, &b, &d);
largest = 1 << b;//范圍
path[0] = 0;
len = 1;
Dfs(0);
for (i = 0; i < len; i++)
{
if ((i + 1) % 10 == 0)
{
printf("%d\n", path[i]);
}
else if (i + 1 != len)
{
printf("%d ", path[i]);
}
else
{
printf("%d\n", path[i]);
}
}
fclose(stdin);
fclose(stdout);
return 0;
}