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


输出很鸡歪 

/*
ID: des_jas1
PROG: hamming
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cmath>
#include <algorithm>
//#define fin cin
//#define fout cout
using namespace std;

const int mmax=70,maxx=9;
int N,B,D,num=0,top,a=0,k=0,digit[maxx],cd[mmax][maxx]={0};
ofstream fout("hamming.out");
ifstream fin("hamming.in");

void print()
{
	a=0;
	int i;
	for(i=0;i<top;i++)
	{
		cd[num-1][i]=digit[i]; //copy
		a+=digit[i]*(1<<i); //1<<i = 2^i
	}
	if(!k)
	{
		fout<<a;
		k++;
	}
	else
	{
		k++;
		fout<<" "<<a;
    	if(k==10)
		{
	   	    k=0;
	    	fout<<endl; 
		}
	}
}

void init() //与0先
{
	int i,n=D-1;
	memset(digit,0,sizeof(digit));
	digit[top-1]=1;
	for(i=0;i<n;i++)
		digit[i]=1;
}

void change() // +1 in binary notation 保证从小到大
{
	int i=0;
	while(digit[i] && i<top)
	{		
		digit[i]=0;
		i++;
	}
	if(i==top)
	{
		top++;
		init();
	}
	else
		digit[i]=1;

}

bool ok() //判断是否和其他所有已经输出的codewords相差至少D个数位

{ int i,j,n; for(i=0;i<num;i++) { n=0; for(j=0;j<top;j++) if(digit[j] != cd[i][j]) n++; if(n<D) return false; } return true; } void search() { init(); for(;;) { if(ok()) { num++; print(); } if(num==N) break; change(); } } int main() { fin>>N>>B>>D; num++; fout<<a; k++; top=D; if(num<N) search(); if(k) //没这个 有个test会多一个 fout<<endl; fout.close(); fin.close(); return 0; }


你可能感兴趣的:(Hamming Codes)