Nadesłany przez Tomasz Lubiński, 23 września 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.
BarCode.java:
/** * @author Tomasz Lubinski * (c)2007 algorytm.org * * ITF-14 Bar Code */ public class BarCode { private static final char codeI25sign[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private static final char codeI25bars[][] = { {'N', 'N', 'W', 'W', 'N'}, {'W', 'N', 'N', 'N', 'W'}, {'N', 'W', 'N', 'N', 'E'}, {'W', 'W', 'N', 'N', 'N'}, {'N', 'N', 'W', 'N', 'W'}, {'W', 'N', 'W', 'N', 'N'}, {'N', 'W', 'W', 'N', 'N'}, {'N', 'N', 'N', 'W', 'W'}, {'W', 'N', 'N', 'W', 'N'}, {'N', 'W', 'N', 'W', 'N'} }; private static final char start[] = { 1, 0, 1, 0 }; private static final char stop[] = { 1, 1, 0, 1 }; public boolean check(String txt) { if (txt.length() != 14) return false; for (int i=0; i<txt.length(); i++) { if (checkLetter(txt.charAt(i)) == false) return false; } if (checkDigit(txt) != txt.charAt(13)) return false; return true; } private boolean checkLetter(char ch) { for (int i=0; i<codeI25sign.length; i++) { if (codeI25sign[i] == ch) return true; } return false; } public char[] getBars(char odd, char even) { char result[] = new char[14]; int current = 0; char bars[] = codeI25bars[getLetterValue(odd)]; char spaces[] = codeI25bars[getLetterValue(even)]; for (int i=0; i<bars.length; i++) { if (bars[i] == 'W') { result[current] = 1; result[current+1] = 1; current += 2; } else { result[current] = 1; current += 1; } if (spaces[i] == 'W') { current += 2; } else { current += 1; } } return result; } //returns letter value for check digit private int getLetterValue(char ch) { for (int i=0; i<codeI25sign.length; i++) if (codeI25sign[i] == ch) return i; return 0; } // return check digit public char checkDigit(String txt) { int sum = 3 * getLetterValue(txt.charAt(0)) + 1 * getLetterValue(txt.charAt(1)) + 3 * getLetterValue(txt.charAt(2)) + 1 * getLetterValue(txt.charAt(3)) + 3 * getLetterValue(txt.charAt(4)) + 1 * getLetterValue(txt.charAt(5)) + 3 * getLetterValue(txt.charAt(6)) + 1 * getLetterValue(txt.charAt(7)) + 3 * getLetterValue(txt.charAt(8)) + 1 * getLetterValue(txt.charAt(9)) + 3 * getLetterValue(txt.charAt(10)) + 1 * getLetterValue(txt.charAt(11)) + 3 * getLetterValue(txt.charAt(12)); sum %= 10; sum = 10 - sum; sum %= 10; return codeI25sign[sum]; } public char[] getStartBars() { return start; } public char[] getStopBars() { return stop; } }