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: 6 1 0 3 12 9 24
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
-
\$\begingroup\$ Related to Luhn algorithm for verifying credit card numbers, possibly a dupe. \$\endgroup\$xnor– xnor2017年11月15日 17:58:44 +00:00Commented Nov 15, 2017 at 17:58
-
1\$\begingroup\$ This question is not actually about a bar code (which is the black-white striped thing), but about the number encoded by a barcode. The number can exist without a bar code, and the bar code can encode other things than EANs. Maybe just "Is my EAN-8 valid" is a better title? \$\endgroup\$Paŭlo Ebermann– Paŭlo Ebermann2017年11月15日 19:49:22 +00:00Commented Nov 15, 2017 at 19:49
-
2\$\begingroup\$ @PaŭloEbermann doesn't quite have the same ring to it... \$\endgroup\$FlipTack– FlipTack2017年11月15日 20:17:02 +00:00Commented Nov 15, 2017 at 20:17
-
8\$\begingroup\$ When reading about barcodes, I expect some image reading (or at least a bit-string), not verifying a checksum. \$\endgroup\$Paŭlo Ebermann– Paŭlo Ebermann2017年11月15日 20:19:40 +00:00Commented Nov 15, 2017 at 20:19
-
\$\begingroup\$ Strongly related, since an ISBN-13 is an EAN. \$\endgroup\$Olivier Grégoire– Olivier Grégoire2017年11月16日 14:55:56 +00:00Commented Nov 16, 2017 at 14:55
60 Answers 60
JavaScript (ES6), (削除) 41 (削除ここまで) (削除) 40 (削除ここまで) 38 bytes
Saved 2 bytes thanks to @ETHProductions and 1 byte thanks to @Craig Ayre.
s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1
Takes input as a list of digits.
Determines the sum of all digits, including the checksum.
If the sum is a multiple of 10, then it's a valid barcode.
Test Cases
let f=
s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1
console.log(f([2,0,3,7,8,2,4,0]));
console.log(f([3,3,7,6,5,1,2,9]));
console.log(f([7,7,2,3,4,5,7,5]));
console.log(f([0,0,0,0,0,0,0,0]));
console.log(f([2,1,0,3,4,9,8,4]));
console.log(f([6,9,1,6,5,4,3,0]));
console.log(f([1,1,9,6,5,4,2,1]));
console.log(f([1,2,3,4,5,6,7,8]));
-
\$\begingroup\$ I was going to say you could save 3 bytes by switching from pre-recursion to post-recursion with
g=([n,...s],i=3,t=0)=>n?g(s,4-i,t+n*i):t%10<1, but you may have found a better way... \$\endgroup\$ETHproductions– ETHproductions2017年11月15日 16:45:14 +00:00Commented Nov 15, 2017 at 16:45 -
\$\begingroup\$ Thanks, @ETHproductions, I've changed to
map, which I think works better since input can be a list of digits instead of a string. \$\endgroup\$Rick Hitchcock– Rick Hitchcock2017年11月15日 16:48:22 +00:00Commented Nov 15, 2017 at 16:48 -
\$\begingroup\$ Perhaps save another byte with
s=>s.map(e=>t+=e*(i=4-i),t=i=1)&&t%10==1? \$\endgroup\$ETHproductions– ETHproductions2017年11月15日 16:48:32 +00:00Commented Nov 15, 2017 at 16:48 -
\$\begingroup\$ Yes, brilliant, thanks : ) \$\endgroup\$Rick Hitchcock– Rick Hitchcock2017年11月15日 16:50:14 +00:00Commented Nov 15, 2017 at 16:50
-
\$\begingroup\$ Great solution! Could you replace
&&with|to output 1/0 since truthy/falsy is allowed? \$\endgroup\$Craig Ayre– Craig Ayre2017年11月15日 17:22:12 +00:00Commented Nov 15, 2017 at 17:22
Jelly, 8 bytes
m2Ḥ+μS5ḍ
Jelly, 9 bytes
×ばつμS5ḍ
Try it online or Try the test suite.
How this works
m2Ḥ+μS5ḍ ~ Full program. m2 ~ Modular 2. Return every second element of the input. Ḥ ~ Double each. +μ ~ Append the input and start a new monadic chain. S ~ Sum. 5ḍ ~ Is divisible by 10?
×ばつμS5ḍ ~ Full program (monadic). J ~ 1-indexed length range. Ḃ ~ Bit; Modulo each number in the range above by 2. Ḥ ~ Double each. ‘ ~ Increment each. ×ばつ ~ Pairwise multiplication with the input. μ ~ Starts a new monadic chain. S ~ Sum. 5ḍ ~ Is the sum divisible by 10?
The result for the first 7 digits of the barcode and the checksum digit must add to a multiple of 10 for it to be valid. Thus, the checksum is valid iff the algorithm applied to the whole list is divisible by 10.
-
\$\begingroup\$ Still 9 bytes but with consistent values:
JḂḤ‘×µS5ḍ\$\endgroup\$2017年11月15日 16:59:47 +00:00Commented Nov 15, 2017 at 16:59 -
\$\begingroup\$ @HyperNeutrino Thanks, I knew there was an atom for this! \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年11月15日 17:00:33 +00:00Commented Nov 15, 2017 at 17:00
-
\$\begingroup\$ Also 9 bytes:
JḂaḤ+µS5ḍ:P \$\endgroup\$2017年11月15日 17:04:41 +00:00Commented Nov 15, 2017 at 17:04 -
\$\begingroup\$ @HyperNeutrino Well there are a lot of alternatives :P \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年11月15日 17:05:35 +00:00Commented Nov 15, 2017 at 17:05
-
1\$\begingroup\$ 8 bytes or 8 characters?
m2Ḥ+µS5ḍis 15 bytes in UTF-8, unless I've calculated it wrong. \$\endgroup\$ta.speot.is– ta.speot.is2017年11月18日 08:31:48 +00:00Commented Nov 18, 2017 at 8:31
MATL, 10 bytes
Thanks to @Zgarb for pointing out a mistake, now corrected.
IlhY"s10\~
Try it online! Or verify all test cases.
Explanation
Ilh % Push [1 3]
Y" % Implicit input. Run-length decoding. For each entry in the
% first input, this produces as many copies as indicated by
% the corresponding entry of the second input. Entries of
% the second input are reused cyclically
s % Sum of array
10\ % Modulo 10
~ % Logical negate. Implicit display
Befunge-98 (PyFunge), (削除) 16 (削除ここまで) 14 bytes
Saved 2 bytes by skipping the second part using j instead of ;s, as well as swapping a ~ and + in the first part to get rid of a + in the second.
~3*+~+6jq!%a+2
Input is in 8 digits (with leading 0s if applicable) and nothing else.
Outputs via exit code (open the debug dropdown on TIO), where 1 is true and 0 is false.
Explanation
This program uses a variety of tricks.
First of all, it takes the digits in one by one through their ASCII values. Normally, this would require subtracting 48 from each value as we read it from the input. However, if we don't modify it, we are left with 16 (3+1+3+1+3+1+3+1) extra copies of 48 in our sum, meaning our total is going to be 768 greater than what it "should" be. Since we are only concerned with the sum mod 10, we can just add 2 to the sum later. Thus, we can take in raw ASCII values, saving 6 bytes or so.
Secondly, this code only checks if every other character is an EOF, because the input is guaranteed to be only 8 characters long.
(削除) Thirdly, the # at the end of the line doesn't skip the first character, but will skip the ; if coming from the other direction. This is better than putting a #; at the front instead. (削除ここまで)
Because the second part of our program is only run once, we don't have to set it up so that it would skip the first half when running backwards. This lets us use the jump command to jump over the second half, as we exit before executing it going backwards.
Step by step
Note: "Odd" and "Even" characters are based on a 0-indexed system. The first character is an even one, with index 0.
~3*+~+ Main loop - sum the digits (with multiplication)
~ If we've reached EOF, reverse; otherwise take char input. This will always
be evenly indexed values, as we take in 2 characters every loop.
3*+ Multiply the even character by 3 and add it to the sum.
~ Then, take an odd digit - we don't have to worry about EOF because
the input is always 8 characters.
+ And add it to the sum.
6j Jump over the second part - We only want to run it going backwards.
q!%a+2 The aftermath (get it? after-MATH?)
+2 Add 2 to the sum to make up for the offset due to reading ASCII
%a Mods the result by 10 - only 0 if the bar code is valid
! Logical not the result, turning 0s into 1s and anything else into 0s
q Prints the top via exit code and exits
C, (削除) 78 (削除ここまで) 77 bytes
i,s,c,d=10;f(b){for(i=s=0,c=b%d;b/=d;)s+=b%d*(3-i++%2*2);return(d-s%d)%d==c;}
C (gcc), 72 bytes
i,s,c,d=10;f(b){for(i=s=0,c=b%d;b/=d;)s+=b%d*(i++%2?:3);b=(d-s%d)%d==c;}
Wolfram Language (Mathematica), (削除) 26 (削除ここまで) 21 bytes
10∣(2-9^Range@8).#&
Takes input as a list of 8 digits.
How it works
2-9^Range@8 is congruent modulo 10 to 2-(-1)^Range@8, which is {3,1,3,1,3,1,3,1}. We take the dot product of this list with the input, and check if the result is divisible by 10.
Wolfram Language (Mathematica), 33 bytes and non-competing
Check[#~BarcodeImage~"EAN8";1,0]&
Takes input as a string. Returns 1 for valid barcodes and 0 for invalid ones.
How it works
The best thing I could find in the way of a built-in (since Mathematica is all about those).
The inside bit, #~BarcodeImage~"EAN8";1, generates an image of the EAN8 barcode, then ignores it entirely and evaluates to 1. However, if the barcode is invalid, then BarcodeImage generates a warning, which Check catches, returning 0 in that case.
-
3\$\begingroup\$ Are you doing the calculation by hand because it's shorter, or because Wolfram doesn't yet have a ValidateEAN8BarCode() function somewhere in its standard library? \$\endgroup\$Mark– Mark2017年11月16日 00:44:52 +00:00Commented Nov 16, 2017 at 0:44
-
1\$\begingroup\$ @Mark Mathematica can't validate the barcode directly, but I just found
BarcodeImage, which generates the image of the barcode, and validates the barcode in the process. SoCheck[#~BarcodeImage~"EAN8";0,1]<1&would work (but it's longer). \$\endgroup\$Misha Lavrov– Misha Lavrov2017年11月16日 00:50:45 +00:00Commented Nov 16, 2017 at 0:50
Jelly, 7 bytes
s2Sḅ35ḍ
How it works
s2Sḅ35ḍ Main link. Argument: [a,b,c,d,e,f,g,h] (digit array)
s2 Split into chunks of length 2, yielding [[a,b], [c,d], [e,f], [g,h]].
S Take the sum of the pairs, yielding [a+c+e+g, b+d+f+h].
ḅ3 Convert from ternary to integer, yielding 3(a+c+e+g) + (b+d+f+h).
5ḍ Test if the result is divisible by 10.
Haskell, (削除) 40 (削除ここまで) 38 bytes
a=3:1:a
f x=mod(sum$zipWith(*)a x)10<1
Takes input as a list of 8 integers. A practical example of using infinite lists.
Edit: Saved 2 bytes thanks to GolfWolf
-
2\$\begingroup\$ Using a recursive definition instead of
cyclesaves 2 bytes. \$\endgroup\$Cristian Lupascu– Cristian Lupascu2017年11月16日 07:50:58 +00:00Commented Nov 16, 2017 at 7:50
Java 8, (削除) 58 (削除ここまで) (削除) 56 (削除ここまで) 55 bytes
a->{int r=0,m=1;for(int i:a)r+=(m^=2)*i;return r%10<1;}
-2 bytes indirectly thanks to @RickHitchcock, by using (m=4-m)*i instead of m++%2*2*i+i after seeing it in his JavaScript answer.
-1 byte indirectly thanks to @ETHProductions (and @RickHitchcock), by using (m^=2)*i instead of (m=4-m)*i.
Explanation:
a->{ // Method with integer-array parameter and boolean return-type
int r=0, // Result-sum
m=1; // Multiplier
for(int i:a) // Loop over the input-array
r+= // Add to the result-sum:
(m^=2) // Either 3 or 1,
*i; // multiplied by the digit
// End of loop (implicit / single-line body)
return r%10<1; // Return if the trailing digit is a 0
} // End of method
-
1\$\begingroup\$ You can save another byte with a trick @ETHProductions showed me: change
m=4-mtom^=2. \$\endgroup\$Rick Hitchcock– Rick Hitchcock2017年11月16日 18:39:39 +00:00Commented Nov 16, 2017 at 18:39 -
\$\begingroup\$ @RickHitchcock Ah, of course.. I use
^=1pretty often in answers when I want to alter between0and1.^=2works in this case to alter between1and3. Nice trick, and thanks for the comment to mention it. :) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年11月16日 18:49:01 +00:00Commented Nov 16, 2017 at 18:49
-
\$\begingroup\$ Seems to fail on
3100004(should be truthy). \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:15:24 +00:00Commented Nov 15, 2017 at 16:15 -
\$\begingroup\$ @Zgarb You're missing a
0there. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年11月15日 16:15:51 +00:00Commented Nov 15, 2017 at 16:15 -
\$\begingroup\$ Oh, it takes a string? Okay then, my bad. \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:17:20 +00:00Commented Nov 15, 2017 at 16:17
-
\$\begingroup\$ @Zgarb Well, you can omit the quotes, but yes, you do need the leading
0. This answer actually uses number functions on strings, one of the features of 05AB1E. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年11月15日 16:20:36 +00:00Commented Nov 15, 2017 at 16:20 -
\$\begingroup\$ @Mr.Xcoder The question isn't very clear on that, I'll add another code which does handle for that below. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年11月15日 16:23:39 +00:00Commented Nov 15, 2017 at 16:23
Pyth, 8 bytes
!es+*2%2
Pyth, 13 bytes
If we can assume the input always has exactly 8 digits:
!es.e*bhy%hk2
How does this work?
!es+*2%2 ~ Full program. %2 ~ Input[::2]. Every second element of the input. *2 ~ Double (repeat list twice). + ~ Append the input. s ~ Sum. e ~ Last digit. ! ~ Logical NOT.
!es.e*sbhy%hk2 ~ Full program. ~ Convert the input to a String. .e ~ Enumerated map, storing the current value in b and the index in k. %hk2 ~ Inverted parity of the index. (k + 1) % 2. hy ~ Double, increment. This maps odd integers to 1 and even ones to 3. b ~ The current digit. * ~ Multiply. s ~ Sum. e ~ Last digit. ! ~ Logical negation.
If the sum of the first 7 digit after being applied the algorithm is subtracted from 10 and then compared to the last digit, this is equivalent to checking whether the sum of all the digits, after the algorithm is applied is a multiple of 10.
-
\$\begingroup\$ Seems to fail on
3100004(should be truthy). \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:13:15 +00:00Commented Nov 15, 2017 at 16:13 -
\$\begingroup\$ @Zgarb Wait should we do
3*3+1*1+0*3+...or0*3+3*1+1*0..? I thought we are supposed to do the former \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年11月15日 16:14:56 +00:00Commented Nov 15, 2017 at 16:14 -
\$\begingroup\$ In the new spec, leading digits are added to ensure there are exactly 8 (if I understand correctly). \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:16:17 +00:00Commented Nov 15, 2017 at 16:16
-
\$\begingroup\$ @Zgarb Ok, fixed. \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年11月15日 16:18:36 +00:00Commented Nov 15, 2017 at 16:18
Retina, (削除) 23 (削除ここまで) 22 bytes
-1 byte thanks to Martin Ender!
(.).
1ドル1ドル$&
.
$*
M`
1$
Explanation
Example input: 20378240
(.).
1ドル1ドル$&
Replace each couple of digits with the first digit repeated twice followed by the couple itself.
We get 2220333788824440
.
$*
Convert each digit to unary. With parentheses added for clarity, we get (11)(11)(11)()(111)(111)...
M`
Count the number of matches of the empty string, which is one more than the number of ones in the string. (With the last two steps we have basically taken the sum of each digit +1) Result: 60
1$
Match a 1 at the end of the string. We have multiplied digits by 3 and 1 alternately and summed them, for a valid barcode this should be divisible by 10 (last digit 0); but we also added 1 in the last step, so we want the last digit to be 1. Final result: 1.
-
2\$\begingroup\$ I think you can drop the
.on the match stage and match1$at the end. \$\endgroup\$Martin Ender– Martin Ender2017年11月16日 10:46:30 +00:00Commented Nov 16, 2017 at 10:46 -
\$\begingroup\$ @MartinEnder very nice, I'll do that, thanks! \$\endgroup\$Leo– Leo2017年11月16日 21:32:26 +00:00Commented Nov 16, 2017 at 21:32
PowerShell, 85 bytes
param($a)(10-(("$a"[0..6]|%{+"$_"*(3,1)[$i++%2]})-join'+'|iex)%10)%10-eq+"$("$a"[7])"
Try it online! or Verify all test cases
Implements the algorithm as defined. Takes input $a, pulls out each digit with "$a"[0..6] and loops through them with |%{...}. Each iteration, we take the digit, cast it as a string "$_" then cast it as an int + before multiplying it by either 3 or 1 (chosen by incrementing $i modulo 2).
Those results are all gathered together and summed -join'+'|iex. We take that result mod 10, subtract that from 10, and again take the result mod 10 (this second mod is necessary to account for the 00000000 test case). We then check whether that's -equal to the last digit. That Boolean result is left on the pipeline and output is implicit.
-
\$\begingroup\$ Seems to fail on
3100004(should be truthy). \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:14:31 +00:00Commented Nov 15, 2017 at 16:14 -
\$\begingroup\$ @Zgarb Works for me? Try it online! \$\endgroup\$AdmBorkBork– AdmBorkBork2017年11月15日 16:31:11 +00:00Commented Nov 15, 2017 at 16:31
-
\$\begingroup\$ Ah ok, I tested it without the quotes. \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:33:25 +00:00Commented Nov 15, 2017 at 16:33
-
\$\begingroup\$ @Zgarb Ah, yeah. Without the quotes, PowerShell will implicitly cast as an integer, stripping the leading zero(s). \$\endgroup\$AdmBorkBork– AdmBorkBork2017年11月15日 16:36:16 +00:00Commented Nov 15, 2017 at 16:36
-
\$\begingroup\$ Nitpick: your TIO timeouts. Also, 16 bytes. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年11月15日 15:37:28 +00:00Commented Nov 15, 2017 at 15:37
-
\$\begingroup\$ @EriktheOutgolfer Wait what how. It works when I put the
Din the footer. And yay thanks! :D \$\endgroup\$2017年11月15日 15:39:54 +00:00Commented Nov 15, 2017 at 15:39 -
\$\begingroup\$ @EriktheOutgolfer Am I doing something wrong? Your 16-byter appears to be invalid? \$\endgroup\$2017年11月15日 15:41:04 +00:00Commented Nov 15, 2017 at 15:41
-
\$\begingroup\$ Maybe, it works kinda differently, but yours seems a bit invalid too...specifically I think the last line should be
DµṪ=Ç. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年11月15日 15:42:49 +00:00Commented Nov 15, 2017 at 15:42 -
1\$\begingroup\$ Seems to fail on
3100004(should be truthy). \$\endgroup\$Zgarb– Zgarb2017年11月15日 16:15:04 +00:00Commented Nov 15, 2017 at 16:15
APL (Dyalog), 14 bytes
Equivalent with streetster's solution.
Full program body. Prompts for list of numbers from STDIN.
0=×ばつ8⍴3 1
Is...
0= zero equal to
10| the mod-10 of
+/ the sum of
×ばつ the input times
8⍴3 1 eight elements cyclically taken from [3,1]
?
-
1\$\begingroup\$ You mean APL can't do it in one character from something like Ancient Sumerian or Linear B? \$\endgroup\$Mark– Mark2017年11月17日 00:20:52 +00:00Commented Nov 17, 2017 at 0:20
-
\$\begingroup\$ train: 0=10|-/+2×+/ \$\endgroup\$ngn– ngn2017年11月18日 18:44:14 +00:00Commented Nov 18, 2017 at 18:44
05AB1E, 9 bytes
3X‚7∍*OTÖ
3X‚7∍*OTÖ # Argument a
3X‚ # Push [3, 1]
7∍ # Extend to length 7
* # Multiply elements with elements at same index in a
O # Total sum
TÖ # Divisible by 10
-
\$\begingroup\$ Nice! First thing I thought was "extend to length" when I saw this, haven't used that one yet. \$\endgroup\$Magic Octopus Urn– Magic Octopus Urn2017年11月17日 22:17:07 +00:00Commented Nov 17, 2017 at 22:17
-
\$\begingroup\$
31×S*OTÖfor 8 bytes.×just pushes 31nnumber of times. When you multiply, it automatically drops the extra 31's. \$\endgroup\$Magic Octopus Urn– Magic Octopus Urn2017年11月17日 22:21:39 +00:00Commented Nov 17, 2017 at 22:21 -
\$\begingroup\$ @MagicOctopusUrn That seems to fail on the 6th testcase
69165430 -> 1\$\endgroup\$kalsowerus– kalsowerus2017年11月17日 23:25:42 +00:00Commented Nov 17, 2017 at 23:25
J, 17 bytes
-10 bytes thanks to cole
0=10|1#.(83ドル 1)*]
This uses multiplication of equal sized lists to avoid the zip/multiply combo of the original solution, as well as the "base 1 trick" 1#. to add the products together. The high level approach is similar to the original explanation.
original, 27 bytes
0=10|{:+[:+/[:*/(73ドル 1),:}:
explained
0 = is 0 equal to...
10 | the remainder when 10 divides...
{: + the last input item plus...
[: +/ the sum of...
[: */ the pairwise product of...
7$(3 1) ,: 3 1 3 1 3 1 3 zipped with...
}: all but the last item of the input
-
\$\begingroup\$
0=10|1#.(83ドル 1)*]should work for 17 bytes (does the same algorithm, too). I'm pretty sure that in the beta you can have a hook ended on the right side with a noun, so0=10|1#.]*83ドル 1may work for 15 (I'd check on tio but it seems to be down?) \$\endgroup\$cole– cole2017年11月16日 08:06:51 +00:00Commented Nov 16, 2017 at 8:06 -
\$\begingroup\$ @cole, I love this improvement. I've learned about and forgotten the
1#.trick like 2 or 3 times... thanks for reminding me. Oh btw the 15 byte version did not work in TIO. \$\endgroup\$Jonah– Jonah2017年11月16日 14:06:01 +00:00Commented Nov 16, 2017 at 14:06
C (gcc), (削除) 84 (削除ここまで) (削除) 82 (削除ここまで) (削除) 72 (削除ここまで) (削除) 61 (削除ここまで) 54 bytes
c;i;f(x){for(i=c=0;x;x/=10)c+=(1+2*i++%4)*x;c=c%10<1;}
-21 bytes from Neil
-7 bytes from Nahuel Fouilleul
Developed independently of Steadybox's answer
'f' is a function that takes the barcode as an int, and returns 1 for True and 0 for False.
fstores the last digit ofxins(s=x%10),Then calculates the sum in
c(for(i=c=0;x;x/=10)c+=(1+2*i++%4)*x;)cis the sum,iis a counterfor each digit including the first, add
1+2*i%4times the digit (x%10) to the checksum and incrementi(thei++in3-2*i++%4)1+2*i%4is 1 wheniis even and 0 wheniis odd
Then returns whether the sum is a multiple of ten, and since we added the last digit (multiplied by 1), the sum will be a multiple of ten iff the barcode is valid. (uses GCC-dependent undefined behavior to omit
return).
-
\$\begingroup\$ I think
(x%10)can just bexas you're takingc%10later anyway. Also I think you can usei<8and then just test whetherc%10is zero at the end. \$\endgroup\$Neil– Neil2017年11月15日 16:30:43 +00:00Commented Nov 15, 2017 at 16:30 -
\$\begingroup\$ @Neil Thanks! That got -10 bytes. \$\endgroup\$pizzapants184– pizzapants1842017年11月15日 16:49:03 +00:00Commented Nov 15, 2017 at 16:49
-
\$\begingroup\$ In fact I think
sis unnecessary:c;i;f(x){for(i=c=0;i<8;x/=10)c+=(1+2*i++%4)*x;return c%10<1;}\$\endgroup\$Neil– Neil2017年11月15日 16:59:57 +00:00Commented Nov 15, 2017 at 16:59 -
\$\begingroup\$ the tio link is 61 bytes but in the answer it's 72, also don't know why
x=c%10<1orc=c%10<1instead ofreturn c%10<1still works \$\endgroup\$Nahuel Fouilleul– Nahuel Fouilleul2017年11月16日 13:03:37 +00:00Commented Nov 16, 2017 at 13:03 -
\$\begingroup\$ also
i<8can be replaced byx\$\endgroup\$Nahuel Fouilleul– Nahuel Fouilleul2017年11月16日 13:07:27 +00:00Commented Nov 16, 2017 at 13:07
C, 63 bytes
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10;}
Assumes that 0 is true and any other value is false.
+3 bytes for better return value
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10==0;}
Add ==0 to the return statement.
Ungolfed
int check(int* values)
{
int result = 0;
for (int index = 0; index < 8; index++)
{
result += v[i] * 3 + v[++i]; // adds this digit times 3 plus the next digit times 1 to the result
}
return result % 10 == 0; // returns true if the result is a multiple of 10
}
This uses the alternative definition of EAN checksums where the check digit is chosen such that the checksum of the entire barcode including the check digit is a multiple of 10. Mathematically this works out the same but it's a lot simpler to write.
Initialising variables inside loop as suggested by Steadybox, 63 bytes
i;s;c(int*v){for(i=s=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10;}
Removing curly brackets as suggested by Steadybox, 61 bytes
i;s;c(int*v){for(i=s=0;i<8;i++)s+=v[i]*3+v[++i];return s%10;}
Using <1 rather than ==0 for better return value as suggested by Kevin Cruijssen
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10<1;}
Add <1 to the return statement, this adds only 2 bytes rather than adding ==0 which adds 3 bytes.
-
\$\begingroup\$ You can save two bytes by removing the
{}after thefor. Also, function submissions have to be reusable, so you need to initializesinside the function (just changei;s=0;toi,s;andi=0;toi=s=0;). \$\endgroup\$Steadybox– Steadybox2017年11月16日 20:44:41 +00:00Commented Nov 16, 2017 at 20:44 -
\$\begingroup\$ @Steadybox How can I remove the curly brackets? \$\endgroup\$micheal65536– micheal655362017年11月16日 21:01:59 +00:00Commented Nov 16, 2017 at 21:01
-
\$\begingroup\$ There's only one statement inside them. When there are no curly brackets after
for, the loop body will be the next statement.for(i=0;i<8;i++){s+=v[i]*3+v[++i];}is the same asfor(i=0;i<8;i++)s+=v[i]*3+v[++i];. \$\endgroup\$Steadybox– Steadybox2017年11月16日 22:32:43 +00:00Commented Nov 16, 2017 at 22:32 -
\$\begingroup\$ @Steadybox Oh of course. That's one of the quirks of C syntax that I usually forget about, because when writing normal code I always include the curly brackets even if they're unnecessary, because it makes the code more readable. \$\endgroup\$micheal65536– micheal655362017年11月16日 22:51:10 +00:00Commented Nov 16, 2017 at 22:51
-
\$\begingroup\$ In your true/false answer, instead of +3 by adding
==0it can be +2 by using<1instead. :) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年11月17日 09:05:10 +00:00Commented Nov 17, 2017 at 9:05
JavaScript (Node.js), 47 bytes
e=>eval(e.map((a,i)=>(3-i%2*2)*a).join`+`)%10<1
Although there is a much shorter answer already, this is my first attempt of golfing in JavaScript so I'd like to hear golfing recommendations :-)
Testing
let f=
e=>eval(e.map((a,i)=>(3-i%2*2)*a).join`+`)%10<1
console.log(f([2,0,3,7,8,2,4,0]));
console.log(f([3,3,7,6,5,1,2,9]));
console.log(f([7,7,2,3,4,5,7,5]));
console.log(f([0,0,0,0,0,0,0,0]));
console.log(f([2,1,0,3,4,9,8,4]));
console.log(f([6,9,1,6,5,4,3,0]));
console.log(f([1,1,9,6,5,4,2,1]));
console.log(f([1,2,3,4,5,6,7,8]));
Alternatively, you can Try it online!
Perl 5, (削除) 37 (削除ここまで) 32 + 1 (-p) bytes
s/./$-+=$&*(--$|*2+1)/ge;$_=/0$/
-5 bytes thanks to Dom Hastings. 37 +1 bytes was
$s+=$_*(++$i%2*2+1)for/./g;$_=!!$s%10
-
1\$\begingroup\$ Had a little play with this and thought I'd share a useful trick:
--$|toggles between1and0so you can use that instead of++$i%2for an alternating boolean! Also, all that matters is that the total ($s) matches/0$/, managed to get 33 bytes combining those changes withs///: Try it online! (-lis just for visibility) \$\endgroup\$Dom Hastings– Dom Hastings2017年11月16日 12:01:49 +00:00Commented Nov 16, 2017 at 12:01 -
\$\begingroup\$ yes i though to
s/./(something with $&)/geand to/0$/match but not the two combined. \$\endgroup\$Nahuel Fouilleul– Nahuel Fouilleul2017年11月16日 12:36:25 +00:00Commented Nov 16, 2017 at 12:36
Brainfuck, 228 Bytes
>>>>++++[<++>-]<[[>],>>++++++[<++++++++>-]<--[<->-]+[<]>-]>[->]<<<<[[<+>->+<]<[>+>+<<-]>>[<+>-]<<<<<]>>>>[>>[<<[>>+<<-]]>>]<<<++++[<---->-]+++++[<++<+++>>-]<<[<[>>[<<->>-]]>[>>]++[<+++++>-]<<-]<[[+]-<]<++++++[>++[>++++<-]<-]>>+.
Can probably be improved a fair bit. Input is taken 1 digit at a time, outputs 1 for true, 0 for false.
How it works:
>>>>++++[<++>-]<
Put 8 at position 3.
[[>],>>++++++[<++++++++>-]<--[<->-]+[<]>-]
Takes input 8 times, changing it from the ascii value to the actual value +2 each time. Inputs are spaced out by ones, which will be removed, to allow for easier multiplication later.
>[->]
Subtract one from each item. Our tape now looks something like
0 0 0 0 4 0 4 0 8 0 7 0 6 0 2 0 3 0 10 0 0
^
With each value 1 more than it should be. This is because zeros will mess up our multiplication process.
Now we're ready to start multiplying.
<<<<
Go to the second to last item.
[[<+>->+<]<[>+>+<<-]>>[<+>-]<<<<<]
While zero, multiply the item it's at by three, then move two items to the left. Now we've multiplied everything we needed to by three, and we're at the very first position on the tape.
>>>>[>>[<<[>>+<<-]]>>]
Sum the entire list.
<<<++++[<---->-]
The value we have is 16 more than the actual value. Fix this by subtracting 16.
+++++[<++<+++>>-]
We need to test whether the sum is a multiple of 10. The maximum sum is with all 9s, which is 144. Since no sum will be greater than 10*15, put 15 and 10 on the tape, in that order and right to the right of the sum.
<<[<[>>[<<->>-]]>[>>]++[<+++++>-]<<-]
Move to where 15 is. While it's non-zero, test if the sum is non-zero. If it is, subtract 10 from it. Now we're either on the (empty) sum position, or on the (also empty) ten position. Move one right. If we were on the sum position, we're now on the non-zero 15 position. If so, move right twice. Now we're in the same position in both cases. Add ten to the ten position, and subtract one from the 15 position.
The rest is for output:
<[[+]-<]<++++++[>++[>++++<-]<-]>>+.
Move to the sum position. If it is non-zero (negative), the barcode is invalid; set the position to -1. Now add 49 to get the correct ascii value: 1 if it's valid, 0 if it's invalid.
Java 8, 53 bytes
Golfed:
b->(3*(b[0]+b[2]+b[4]+b[6])+b[1]+b[3]+b[5]+b[7])%10<1
Direct calculation in the lambda appears to the shortest solution. It fits in a single expression, minimizing the lambda overhead and removing extraneous variable declarations and semicolons.
public class IsMyBarcodeValid {
public static void main(String[] args) {
int[][] barcodes = new int[][] { //
{ 2, 0, 3, 7, 8, 2, 4, 0 }, //
{ 3, 3, 7, 6, 5, 1, 2, 9 }, //
{ 7, 7, 2, 3, 4, 5, 7, 5 }, //
{ 0, 0, 0, 0, 0, 0, 0, 0 }, //
{ 2, 1, 0, 3, 4, 9, 8, 4 }, //
{ 6, 9, 1, 6, 5, 4, 3, 0 }, //
{ 1, 1, 9, 6, 5, 4, 2, 1 }, //
{ 1, 2, 3, 4, 5, 6, 7, 8 } };
for (int[] barcode : barcodes) {
boolean result = f(b -> (3 * (b[0] + b[2] + b[4] + b[6]) + b[1] + b[3] + b[5] + b[7]) % 10 < 1, barcode);
System.out.println(java.util.Arrays.toString(barcode) + " = " + result);
}
}
private static boolean f(java.util.function.Function<int[], Boolean> f, int[] n) {
return f.apply(n);
}
}
Output:
[2, 0, 3, 7, 8, 2, 4, 0] = true
[3, 3, 7, 6, 5, 1, 2, 9] = true
[7, 7, 2, 3, 4, 5, 7, 5] = true
[0, 0, 0, 0, 0, 0, 0, 0] = true
[2, 1, 0, 3, 4, 9, 8, 4] = false
[6, 9, 1, 6, 5, 4, 3, 0] = false
[1, 1, 9, 6, 5, 4, 2, 1] = false
[1, 2, 3, 4, 5, 6, 7, 8] = false
QBasic, (削除) 54 (削除ここまで) 52 bytes
Ugh, the boring answer turned out to be the shortest:
INPUT a,b,c,d,e,f,g,h
?(3*a+b+3*c+d+3*e+f+3*g+h)MOD 10=0
This inputs the digits comma-separated. My original 54-byte solution, which inputs one digit at a time, uses a "nicer" approach:
m=3
FOR i=1TO 8
INPUT d
s=s+d*m
m=4-m
NEXT
?s MOD 10=0
C# (.NET Core), (削除) 65 (削除ここまで) 62 bytes
b=>{int s=0,i=0,t=1;while(i<8)s+=b[i++]*(t^=2);return s%10<1;}
Acknowledgements
-3 bytes thanks to @KevinCruijssen and the neat trick using the exclusive-or operator.
DeGolfed
b=>{
int s=0,i=0,t=1;
while(i<8)
s+=b[i++]*(t^=2); // exclusive-or operator alternates t between 3 and 1.
return s%10<1;
}
C# (.NET Core), 53 bytes
b=>(3*(b[0]+b[2]+b[4]+b[6])+b[1]+b[3]+b[5]+b[7])%10<1
A direct port of @Snowman's answer.
-
\$\begingroup\$ For your first answer:
b=>{int s=0,i=0,t=1;while(i<8)s+=b[i++]*(t^=2);return s%10<1;}(62 bytes), or alternatively with a foreach, also 62 bytes:b=>{int s=0,t=1;foreach(int i in b)s+=i*(t^=2);return s%10<1;}(which is a port of my Java 8 answer). \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年11月17日 08:58:21 +00:00Commented Nov 17, 2017 at 8:58
K (oK), (削除) 16 (削除ここまで) 15 bytes
Solution:
{~10!+/x*8#3 1}
Examples:
{~10!+/x*8#3 1}2 1 0 3 4 9 8 5
1
{~10!+/x*8#3 1}2 1 0 3 4 9 8 4
0
{~10!+/x*8#3 1}2 0 3 7 8 2 4 0
1
Explanation:
K is interpreted right-to-left:
{~10!+/x*8#3 1} / the solution
{ } / lambda with x as implicit input
3 1 / the list [3,1]
8# / 8 take this list = [3,1,3,1,3,1,3,1]
x* / multiply input by this
+/ / sum over the list
10! / 10 mod this sum
~ / not, 0 => 1, anything else => 0
Vyxal, 8 bytes
y3ドル*J∑0Ḋ
y # Uninterleave
$ # Swap
3* # Multiply by 3 (vectorised)
J # Join
∑ # Sum
0Ḋ # Is divisible by 10?
MATLAB/Octave, 32 bytes
@(x)~mod(sum([2*x(1:2:7),x]),10)
I'm going to post this despite the other Octave answer as I developed this code and approach without looking at the other answers.
Here we have an anonymous function which takes the input as an array of 8 values, and return true if a valid barcode, false otherwise..
The result is calculated as follows.
2*x(1:2:7)
[ ,x]
sum( )
mod( ,10)
@(x)~
- Odd digits (one indexed) are multiplied by 2.
- The result is prepended to the input array, giving an array whose sum will contain the odd digits three times, and the even digits once.
- We do the sum which will also include the supplied checksum within our sum.
- Next the modulo 10 is performed. If the checksum supplied was valid, the sum of all multiplied digits including the checksum value would end up being a multiple of 10. Therefore only a valid barcode would return 0.
- The result is inverted to get a logical output of true if valid.
Excel, 37 bytes
Interpreting "A list of 8 integers" as allowing 8 separate cells in Excel:
=MOD(SUM(A1:H1)+2*(A1+C1+E1+G1),10)=0
-
\$\begingroup\$ =MOD(SUM((A1:H1)+2*(A1+C1+E1+G1)),10)=0 this formula exist in Excel? \$\endgroup\$user58988– user589882017年11月23日 21:40:33 +00:00Commented Nov 23, 2017 at 21:40
-
\$\begingroup\$ @RosLuP, not predefined, no. But Modulo, Sum, + etc do ;-) \$\endgroup\$Wernisch– Wernisch2017年11月24日 10:15:01 +00:00Commented Nov 24, 2017 at 10:15
-
\$\begingroup\$ I want only to say that seems that in APL goes well doing first y= (A1:H1)+2*(A1+C1+E1+G1), and after the sum and the mod; in APL not goes well first sum(A1:H1) etc something as (1,2,3)+4=(5,6,7) and than sum(5,6,7)=18; note that sum(1,2,3)=6 and 6+4=10 different from 18. But possible I make error in something \$\endgroup\$user58988– user589882017年11月24日 16:37:02 +00:00Commented Nov 24, 2017 at 16:37
-
\$\begingroup\$ @RosLuP, Apologies, missed the changed
()s in your comment. \$\endgroup\$Wernisch– Wernisch2017年11月24日 16:43:49 +00:00Commented Nov 24, 2017 at 16:43 -
\$\begingroup\$ Problem is how Excel interprets
=(A1:H1): This is not handled as an array. Is invalid if placed in any column not inA-Hrange. If placed in a column in A-H, returns the value for that column only. (Formula in % results in %: C2 --> C1 H999 --> H1 K1 --> #VALUE!) \$\endgroup\$Wernisch– Wernisch2017年11月24日 16:59:04 +00:00Commented Nov 24, 2017 at 16:59
Ruby, 41 Bytes
Takes an array of integers. -6 bytes thanks to Jordan.
->n{n.zip([3,1]*4){|x,y|$.+=x*y};$.%10<1}
-
\$\begingroup\$ Nice! FWIW you don’t need
maphere at all:ziptakes a block. You can save a couple more bytes by using$.instead of initializings:->n{n.zip([3,1]*4){|x,y|$.+=x*y};$.%10<1}\$\endgroup\$Jordan– Jordan2017年11月16日 06:44:49 +00:00Commented Nov 16, 2017 at 6:44
Explore related questions
See similar questions with these tags.