2

I want to calculate all possbie hamming neighbours from a given byte with a maximum hamming distance.

For a hamming distance of 1 I have created this function:

public static ArrayList<Byte> hammingNeighbours(byte input, int maxDistance){
    ArrayList<Byte> neighbours = new ArrayList<>();
    neighbours.add(input);
    byte value;;
    byte mask = 1;


        for (int i = 0; i < 8; i++) {
            value = (byte) (input ^mask);
            neighbours.add(value);
            mask = (byte) (mask << 1);

        }
    return neighbours;
}

But how to add neighbours with a distance > 1? can someone help me to solve this problem?

best regards

501 - not implemented
  • 2,638
  • 4
  • 39
  • 74

2 Answers2

1

As I said in the comments, all the byte which do not have a distance == 1 or 0 would be valid. But if you want an algorithm which will give you all the bytes which are at most maxDist away, you could do a recursive method as such:

public static void getNeighbours(ArrayList<Byte> nbrs, byte input, int bit, int maxDist) {
    if(maxDist == 0 || bit == 8) {
        nbrs.add(input);
    } else {
        getNeighbours(nbrs, (byte) (input^(1<<bit)), bit+1, maxDist-1);
        getNeighbours(nbrs, input, bit+1, maxDist);
    }
}  

If you only want the bytes which are exactly maxDist away, then only add if(maxDist == 0) and terminate the branch if(bit == 8)

Maljam
  • 6,244
  • 3
  • 17
  • 30
0

okay, after simple consideration, I can use my code from the first post and expanse it with a simple recursion to calculate all neighbours:

public static HashSet<Byte> hammingNeighbours(byte input, int maxDistance){
    HashSet<Byte> neighbours = new HashSet<>();
    neighbours.add(input);
    byte value;;
    byte mask = 1;


        for (int i = 0; i < 8; i++) {
            value = (byte) (input ^mask);
            if(maxDistance > 1){
            neighbours.addAll(hammingNeighbours(value,maxDistance -1));
            }
            else{
                neighbours.add(value);
            }
            mask = (byte) (mask << 1);

        }
    return neighbours;
}

you ca test it with this example code:

 HashSet<Byte> bset = hammingNeighbours((byte) 0, 2);
    System.out.println(bset.size());
    for (Byte b : bset) {
        System.out.println(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'));;
    }
501 - not implemented
  • 2,638
  • 4
  • 39
  • 74