Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package hammingdistance;
- import java.io.*;
- import java.util.*;
- import java.math.*;
- public class Main {
- public static String toBinary(int x){
- StringBuilder str = new StringBuilder("");
- for (; ;){
- if ((x & 1) == 1) str = str.append("1");
- else str = str.append("0");
- x >>= 1;
- if (x == 0) break;
- }
- StringBuilder res = new StringBuilder("");
- for (int j = 4 - str.toString().length(); j > 0; j--) res = res.append("0");
- res = res.append(str.reverse());
- return (res.toString());
- }
- public static String generate(int i){
- String str = toBinary(i);
- int p1 = (((int)str.charAt(0) + (int)str.charAt(1) + (int)str.charAt(2)) & 1) + 48;
- int p2 = (((int)str.charAt(0) + (int)str.charAt(1) + (int)str.charAt(3)) & 1) + 48;
- int p3 = (((int)str.charAt(1) + (int)str.charAt(2) + (int)str.charAt(3)) & 1) + 48;
- StringBuilder res = new StringBuilder(str);
- res = res.append((char)p1);
- res = res.append((char)p2);
- res = res.append((char)p3);
- String bin = res.toString();
- return bin;
- }
- public static int Hamming_Distance(String a, String b){
- int res = 0;
- for (int j = 0; j < 7; j++){
- if (a.charAt(j) != b.charAt(j)) res++;
- }
- return res;
- }
- public static void main(String[] args) throws Exception{
- String[] codewords = new String[16];
- for (int i = 0; i < 16; i++){
- codewords[i] = generate(i);
- //System.out.println(codewords[i]);
- }
- //codewords = new String[] {"0000000", "1110000", "1001100", "0111100", "0101010", "1011010", "1100110", "0010110", "1101001", "0011001", "0100101", "1010101", "1000011", "0110011", "0001111", "1111111"};
- final int h = 3;
- Scanner sc = new Scanner(new File("C:\\Users\\Public\\Documents\\what the hell\\data.txt"));
- PrintWriter pw = new PrintWriter(new File("C:\\Users\\Public\\Documents\\what the hell\\lol.txt"));
- int counter = 0;
- while (sc.hasNext()){
- String str = sc.nextLine();
- int len = str.length();
- StringBuilder temp = new StringBuilder("");
- for (int j = 0; j < len; j++){
- int r = (int)(Math.random() * 100);
- r = (r % 5);
- if (r == 0){
- if (str.charAt(j) == '0') temp = temp.append('1');
- else temp = temp.append('0');
- }
- else temp = temp.append(str.charAt(j));
- }
- String error = new String(temp);
- int c = 0;
- for (int j = 0; j < 16; j++){
- int dis = Hamming_Distance(codewords[j], error);
- if (dis < h) c++;
- }
- if (c != 1) counter++;
- if (c == 1) System.out.println("No Error");
- else System.out.println("Error!");
- }
- System.out.println(counter + "Errors Detected");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement