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
-----------------------------------------------------------------------------
关键之处在于:
求两个数字键的海明距离。
x=a xor b ,其中为1的位即表示a和b不同的地方。
只需要计算x中1的个数即可。
对于8位二进制数,计算1的个数的方法是:
x=(x & 0x55555555)+((x>>1)& 0x55555555);
x=(x & 0x33333333)+((x>>2)& 0x33333333);
x=(x & 0x0F0F0F0F)+((x>>4)& 0x0F0F0F0F);
x=(x & 0x00FF00FF)+((x>>8)& 0x00FF00FF);
x=(x & 0x0000FFFF)+((x>>16)& 0x0000FFFF);
经过以上步骤之后,x就是1的个数。
我的程序:
----------------------------------- ----------------------------------------------------------------------
/*
ID: yunleis2
PROG: hamming
LANG: C++
*/
#include<iostream>
#include<fstream>
#include <cmath>
using namespace std;
int N, B, D;
typedef unsigned int uint;
int distance1(uint a,uint b);
int main()
{
fstream fin("hamming.in",ios::in);
fin>>N>>B>>D;
uint src;
uint end=(1<<B)-1;
uint *result= new uint[N];
result[0]=0;
int ptr=1;
for(uint i=1;i<=end;i++)
{
bool flag=true;
for(int j=0;j<ptr;j++)
{
if(distance1(i,result[j])<D)
{
flag=false;
break;
}
}
if(flag)
{
result[ptr++]=i;
}
if(ptr==N)
break;
}
fstream fout("hamming.out",ios::out);
for(int i=0;i<ptr;i++)
{
fout<<result[i];
if(((i+1)%10)==0||i==(ptr-1))
fout<<endl;
else fout<<" ";
}
}
int distance1(uint a,uint b)
{
uint x=a^b;
x=(x & 0x55555555)+((x>>1)& 0x55555555);
x=(x & 0x33333333)+((x>>2)& 0x33333333);
x=(x & 0x0F0F0F0F)+((x>>4)& 0x0F0F0F0F);
x=(x & 0x00FF00FF)+((x>>8)& 0x00FF00FF);
x=(x & 0x0000FFFF)+((x>>16)& 0x0000FFFF);
return x;
}