USACO Training "hamming": Hamming Codes

USACOT "hamming": Hamming Code

Problem Statement

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

The Interpretation and Method

This problem asks us to find a sequence that has at least Hamming distance d away from all other elements. These elements are restricted to bit size B (or at most 2^B). We can find this by simply pruning from all numbers 1~2^B, checking if each number can be added to the list, and if so doing so.
This inspires a simple for loop idea: we first append 0 to the answer list, and then going through 0~2^B, checking the validity of each number by seeing if the Hamming distance between any number in the current list and the testing number is greater than or equal to D. If so, then add this number to the list; once the list has N elements, terminate the loop and print the values out.

The Code Itself

/*
ID: qlstudi3
PROG: hamming
LANG: C++14
*/

#include <cstdio>
#include <bitset>
#include <vector>
using namespace std;


int dist(int x, int y)
{
    bitset<8> b(x^y);
    return b.count();
}

int main(int argc, const char * argv[])
{
    freopen("hamming.in","r",stdin);
    freopen("hamming.out","w",stdout);
    int n,b,Li;
    vector<int> ans;
    ans.push_back(0);
    scanf("%d %d %d",&n,&b,&Li);
    for(int i=0;i!=1<<b;i++)
    {
        bool y=true;
        for(int x:ans)
            y=y&&(dist(i,x)>=Li);
        if(y) ans.push_back(i);
        if(ans.size()==n) break;
    }
    for(int i=0;i<ans.size();i++)
    {
        if(i&&(i%10==0)) printf("\n");
        else if(i) printf(" ");
        printf("%d",ans[i]);
    }
    printf("\n");
    return 0;
}

Comments

Popular posts from this blog

USACO Training "subset": Subset Sums

USACO 2018 Open: Talent Show

UVA 787 and Big Number Multiplication