[Java] Hamming Codes

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: hamming
*/
import java.io.*;
import java.util.*;

public class hamming {
    
    

	private int N;
	private int B;
	private int D;
	private int total;
	
	private boolean isValid(Set<Integer> set, int num) {
    
    
		for (int i : set) {
    
    
			int count = 0;
			int flag = 1;
			for (int j = 0; j < B; j++) {
    
    
				if ((num & flag) != (i & flag)) {
    
    
					count++;
				}
				flag = flag << 1;
			}
			if (count < D) {
    
    
				return false;
			}
		}
		return true;
	}

	private void DFS(Set<Integer> set, int num) {
    
    
		if (set.size() == N) {
    
    
			return;
		}
		for (int i = num; i < total; i++) {
    
    
			if (!isValid(set, i)) {
    
    
				continue;
			}
			set.add(i);
			DFS(set, i + 1);
			if (set.size() == N) {
    
    
				return;
			}
			set.remove(i);
		}
	}

	public hamming() throws IOException {
    
    
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("hamming.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("hamming.out")));

		// Use StringTokenizer vs. readLine/split -- lots faster
		StringTokenizer st = new StringTokenizer(f.readLine());

	    this.N = Integer.parseInt(st.nextToken());
	    this.B = Integer.parseInt(st.nextToken());
	    this.D = Integer.parseInt(st.nextToken());
	    this.total = (int) Math.pow(2, B);
	    Set<Integer> set = new TreeSet<>();
	    DFS(set, 0);
	    int count = 0;
	    for (int codewords : set) {
    
    
	    	count++;
	    	if (count == N) {
    
    
	    		out.println(codewords);
	    		break;
	    	}
	    	if (count % 10 == 0) {
    
    
	    		out.println(codewords);
	    	}
	    	else {
    
    
	    		out.print(codewords + " ");
	    	}
	    }
	    out.close();
	    f.close();
	}
	
	public static void main (String [] args) throws IOException {
    
    
		new hamming();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41714373/article/details/112760062