EAN-8 Barcode, Code golf
/*
An EAN-8 barcode includes 7 digits of information and an 8th checksum digit.
The checksum is calculated by multiplying the digits by 3 and 1 alternately,
adding the results, and subtracting from the next multiple of 10.
For example, given the digits 2103498:
Digit: 2 1 0 3 4 9 8
Multiplier: 3 1 3 1 3 1 3
Result: sum(6 1 0 3 12 9 24) = 55
The sum of these resulting digits is 55,
so the checksum digit is 60 - 55 = 5
The Challenge:
Your task is to, given an 8 digit barcode, verify if it is valid - returning a
truthy value if the checksum is valid, and falsy otherwise.
You may take input in any of the following forms: A string, 8 characters in
length, representing the barcode digits A list of 8 integers, the barcode's
digits A non-negative integer (you can either assume leading zeroes where none
are given, i.e. 1 = 00000001, or request input with the zeroes given) Builtins
that compute the EAN-8 checksum (i.e, take the first 7 digits and calculate the
last) are banned. This is code-golf, so the shortest program (in bytes) wins!
Test Cases
20378240 -> True
33765129 -> True
77234575 -> True
00000000 -> True
21034984 -> False
69165430 -> False
11965421 -> False
12345678 -> False
Solution as follows:
118 chars
By Peter Li
*/
int i,j,k;int main(int,char**v){for(;i<7;(j+=(v[1][i]-48)*(i++%2?1:3)));
for(;(k+=10)<j;);return v[1][7]-48==(k-j)%10;}
Menu