Nadesłany przez Tomasz Lubiński, 20 listopada 2019 21:36
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.
bc412.js:
//BC412 //(c) 2019 by Tomasz Lubinski //www.algorytm.org var bc412chars = [ '0', 'R', '9', 'G', 'L', 'V', 'H', 'A', '8', 'E', 'Z', '4', 'N', 'T', 'S', '1', 'J', '2', 'Q', '6', 'C', '7', 'D', 'Y', 'K', 'B', 'U', 'I', 'X', '3', 'F', 'W', 'P', '5', 'M' ]; var bc412spaces = [ [1, 1, 1, 5], [3, 1, 2, 2], [1, 3, 1, 3], [2, 1, 2, 3], [2, 2, 3, 1], [3, 3, 1, 1], [2, 1, 3, 2], [1, 3, 2, 2], [1, 2, 4, 1], [1, 5, 1, 1], [5, 1, 1, 1], [1, 1, 5, 1], [2, 3, 2, 1], [3, 2, 1, 2], [3, 1, 2, 2], [1, 1, 2, 4], [2, 2, 1, 3], [1, 1, 3, 3], [3, 1, 1, 3], [1, 2, 2, 3], [1, 4, 1, 2], [1, 2, 3, 2], [1, 4, 2, 1], [4, 2, 1, 1], [2, 2, 2, 2], [1, 3, 3, 1], [3, 2, 2, 1], [2, 1, 4, 1], [4, 1, 2, 1], [1, 1, 4, 2], [2, 1, 1, 4], [4, 1, 1, 2], [2, 4, 1, 1], [1, 2, 1, 4], [2, 3, 1, 2] ]; var start = 2; var stop = 1; /* Check if code is correct */ function check(bc412) { for (var i=0; i<bc412.length; i++) { if (getLetterIndex(bc412[i]) == -1) return false; } return true; } /* Return letter index, or -1 if not correct */ function getLetterIndex(ch) { for (var i=0; i<bc412chars.length; i++) { if (bc412chars[i] == ch) return i; } return -1; } function checkDigit(bc412) { var sum = 0; for (var i = 0; i < bc412.length; i++) { sum += getLetterIndex(bc412[i]); } return (sum % 35); } /* Convert code to bars */ function convert(bc412) { /* inccorect code return null */ if (check(bc412) == false) { return null; } var bars = new Array(4*(bc412.length+1) + 2); /* add start bars */ bars[0] = start; /* add character codes */ for (var i=0; i<bc412.length; i++) { var toCopy = bc412spaces[getLetterIndex(bc412[i])]; for (var j=0; j<4; j++) { bars[i * 4 + 1 + j] = toCopy[j]; } } /* add check digit*/ var toCopy = bc412spaces[checkDigit(bc412)]; for (var j = 0; j < 4; j++) { bars[4 * bc412.length + 1 + j] = toCopy[j]; } /* add stop bars */ bars[4 * (bc412.length + 1) + 1] = stop return bars; } //initialize data function generate(bc412) { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); /* clear canvas and set its width */ canvas.width = bc412.length*24+50; /* prepare style */ ctx.fillStyle = "rgb(0,0,0)"; ctx.font = "10pt Arial"; ctx.textBaseline = "top"; ctx.textAlign = "left"; bc412 = bc412.toUpperCase(); bc412 = bc412.replace(/O/g, "0") var bars = convert(bc412); if (bars != null) { var pos = 10; for (i=0; i<bars.length; i++) { /* Draw a bar and shift by requested space */ ctx.fillRect(pos, 10, 2, 70); pos += 2 + bars[i]*2; } for (i=0; i<bc412.length; i++) { ctx.fillText(bc412[i], i*24+20, 90); } } else { ctx.fillText("Nieprawidłowy", 10, 10); ctx.fillText("kod", 10, 25); ctx.fillText("Incorrect", 10, 50); ctx.fillText("code", 10, 65); } }