Nadesłany przez Tomasz Lubiński, 11 kwietnia 2007 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
Verhoeff.java:
//algorytm Verhoeff'a //www.algorytm.org //(c)2007 by Tomasz Lubinski public class Verhoeff { private static final byte d[][] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}}; private static final byte p[][] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}}; private static final byte inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; /** * Check number * @param number * @return true if check digit in number is correct, false otherwise */ public static boolean verhoeffCheck(String number) { int c = 0; int digit; for (int i=0; i<number.length(); i++) { digit = Integer.parseInt(number.charAt(number.length() - i - 1) + ""); c = d[c][p[i%8][digit]]; } if (c == 0) { return true; } return false; } /** * Calculate check digit for a given number * @param number (with check digit with any value) * @return check digit */ public static byte verhoeffCheckDigit(String number) { int c = 0; int digit; for (int i=1; i<number.length(); i++) { digit = Integer.parseInt(number.charAt(number.length() - i - 1) + ""); c = d[c][p[i%8][digit]]; } return inv[c]; } /** * Get number and check it * * @param args */ public static void main(String[] args) { String number; System.out.println("Podaj numer do sprawdzenia"); number = Console.readString(); if (verhoeffCheck(number)) { System.out.println("Numer jest prawidłowy"); } else { System.out.println("Numer jest nieprawidłowy"); System.out.println("Dla tego numeru prawidlowa cyfra kontrolna to " + verhoeffCheckDigit(number)); } } }