Mon code à barres est-il valide?

33

Un code à barres EAN-8 comprend 7 chiffres d'informations et un 8ème chiffre de somme de contrôle.

La somme de contrôle est calculée en multipliant les chiffres par 3 et 1 alternativement, en additionnant les résultats et en soustrayant du multiple de 10 suivant.

Par exemple, étant donné les chiffres 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

La somme de ces chiffres résultants est 55 , le chiffre de la somme de contrôle est donc 60 - 55 = 5


Le défi

Votre tâche consiste à vérifier, à l'aide d'un code à barres de 8 chiffres, si celui-ci est valide - à renvoyer une valeur de vérité si la somme de contrôle est valide.

  • Vous pouvez prendre des contributions sous l’une des formes suivantes:
    • Une chaîne de 8 caractères représentant les chiffres du code à barres
    • Une liste de 8 entiers, les chiffres du code à barres
    • Un entier non négatif (vous pouvez soit supposer des zéros en tête où aucun n'est donné, c'est-à-dire 1= 00000001, soit demander une entrée avec les zéros donnés)
  • Les fonctions intégrées qui calculent la somme de contrôle EAN-8 (c.-à-d., Prennent les 7 premiers chiffres et calculent le dernier) sont interdites.
  • C'est du , donc le programme le plus court (en octets) gagne!

Cas de test

20378240 -> True
33765129 -> True
77234575 -> True
00000000 -> True

21034984 -> False
69165430 -> False
11965421 -> False
12345678 -> False
FlipTack
la source
Relatif à l' algorithme de Luhn pour la vérification des numéros de carte de crédit , éventuellement une dupe.
xnor
1
Cette question ne concerne pas réellement un code à barres (ce qui est la chose rayée noir-blanc), mais sur le nombre encodé par un code à barres. Le numéro peut exister sans code à barres, et le code à barres peut coder des éléments autres que les codes EAN. Peut-être que " Est-ce que mon EAN-8 est valide " est un meilleur titre?
Paŭlo Ebermann
2
@ PaŭloEbermann n'a pas vraiment le même anneau ...
FlipTack
7
Lors de la lecture de codes à barres, j'attends une lecture d'image (ou au moins une chaîne de bits), sans vérification d'une somme de contrôle.
Paŭlo Ebermann
Fortement lié , car un ISBN-13 est un EAN.
Olivier Grégoire

Réponses:

5

Gelée , 7 octets

s2Sḅ3⁵ḍ

Essayez-le en ligne!

Comment ça marche

s2Sḅ3⁵ḍ  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).
     ⁵ḍ  Test if the result is divisible by 10.
Dennis
la source
13

JavaScript (ES6), 41 40 38 octets

2 octets sauvés grâce à @ETHProductions et 1 octet grâce à @Craig Ayre.

s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1

Prend la saisie sous forme de liste de chiffres.

Détermine la somme de tous les chiffres, y compris la somme de contrôle.

Si la somme est un multiple de 10, il s'agit d'un code à barres valide.

Cas de test

Rick Hitchcock
la source
J'allais dire que vous pourriez économiser 3 octets en passant de pré-récursion à post-récursion avec g=([n,...s],i=3,t=0)=>n?g(s,4-i,t+n*i):t%10<1, mais vous avez peut-être trouvé un meilleur moyen ...
ETHproductions
Merci, @ETHproductions, j'ai changé pour map, ce qui, à mon avis, fonctionne mieux, car l'entrée peut être une liste de chiffres au lieu d'une chaîne.
Rick Hitchcock
Peut-être économiser un autre octet avec s=>s.map(e=>t+=e*(i=4-i),t=i=1)&&t%10==1?
ETHproductions
Oui, génial, merci
:)
Excellente solution! Pourriez-vous remplacer &&par |pour sortir 1/0 puisque la vérité / la fausseté est permise?
Craig Ayre
10

Python 2 , 64 48 35 29 octets

mypetlion a enregistré 19 octets

lambda x:sum(x[::2]*2+x)%10<1

Essayez-le en ligne!

Halvard Hummel
la source
lambda x:sum(x[::2]*3+x[1::2])%10<1Pour 35 octets.
mypetlion
2
lambda x:sum(x[::2]*2+x)%10<1Pour 29 octets.
mypetlion
8

Gelée , 8 octets

m2Ḥ+µS⁵ḍ

Essayez la suite de tests.

Gelée , 9 octets

JḂḤ‘×µS⁵ḍ

Essayez-le en ligne ou essayez la suite de tests.

Comment ça marche

m2Ḥ + µS⁵ḍ ~ Programme complet.

m2 ~ Modular 2. Renvoie chaque deuxième élément de l'entrée.
  Ḥ ~ Double chaque.
   + µ ~ Ajouter l'entrée et démarrer une nouvelle chaîne monadique.
     S ~ Sum.
      ~ Est divisible par 10?
JḂḤ '× µS⁵ḍ ~ Programme complet (monadique).

J ~ 1 plage de longueur indexée.
 Ḃ ~ Bit; Modulo chaque nombre dans la plage ci-dessus par 2.
  Ḥ ~ Double chaque.
   ~ Incrémente chacun.
    × ~ Multiplication par paires avec l'entrée.
     µ ~ Démarre une nouvelle chaîne monadique.
      S ~ Sum.
       ~ La somme est-elle divisible par 10?

Le résultat pour les 7 premiers chiffres du code à barres et le chiffre de la somme de contrôle doivent s’ajouter à un multiple de 10 pour que le code soit valide. Ainsi, la somme de contrôle est valide si l’algorithme appliqué à toute la liste est divisible par 10 .

M. Xcoder
la source
Encore 9 octets mais avec des valeurs cohérentes:JḂḤ‘×µS⁵ḍ
HyperNeutrino
@HyperNeutrino Merci, je savais qu'il y avait un atome pour ça!
M. Xcoder
Aussi 9 octets:: JḂaḤ+µS⁵ḍP
HyperNeutrino
@HyperNeutrino Eh bien, il y a beaucoup d'alternatives: P
M. Xcoder
1
8 octets ou 8 caractères? m2Ḥ+µS⁵ḍest de 15 octets en UTF-8, sauf si je l’ai mal calculé.
ta.speot.is
7

MATL , 10 octets

Merci à @Zgarb pour avoir signalé une erreur, maintenant corrigée.

IlhY"s10\~

Essayez-le en ligne! Ou vérifiez tous les cas de test .

Explication

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
Luis Mendo
la source
7

Befunge-98 (PyFunge) , 16 à 14 octets

Sauvegardé 2 octets en sautant la deuxième partie en utilisant jau lieu de ;s, ainsi qu'en échangeant a ~et +dans la première partie pour se débarrasser de a +dans la seconde.

~3*+~+6jq!%a+2

La saisie est en 8 chiffres (avec le 0 en début si applicable) et rien d’autre.

Les sorties via le code de sortie (ouvrez la liste déroulante de débogage sur TIO), où 1 est vrai et 0 est faux.

Essayez-le en ligne!

Explication

Ce programme utilise une variété de trucs.

Tout d'abord, il prend les chiffres un par un à travers leurs valeurs ASCII. Normalement, cela nécessiterait de soustraire 48 à chaque valeur comme nous le lisons à partir de l'entrée. Cependant, si nous ne le modifions pas, il nous reste 16 (3 + 1 + 3 + 1 + 3 + 1 + 3 + 1) copies supplémentaires de 48 dans notre somme, ce qui signifie que notre total va être 768 supérieur à ce qu'il "devrait" être. Comme nous ne sommes concernés que par la somme mod 10, nous pouvons simplement ajouter 2 à la somme plus tard. Ainsi, nous pouvons prendre en valeurs ASCII brutes, économisant environ 6 octets.

Deuxièmement, ce code vérifie uniquement si tous les autres caractères sont des caractères EOF, car il est garanti que la saisie ne comporte que 8 caractères.

Troisièmement, la #fin de la ligne ne saute pas le premier caractère, mais saute le ;si venant de l’autre direction. C'est mieux que de mettre un #;à l'avant à la place.

Étant donné que la deuxième partie de notre programme n’est exécutée qu’une fois, nous n’avons pas besoin de le configurer pour qu’il saute la première moitié lorsqu’il fonctionne à l’arrière. Cela nous permet d'utiliser la commande jump pour sauter par-dessus la seconde moitié, avant de l'exécuter en arrière.

Pas à pas

Remarque: les caractères "impairs" et "pairs" sont basés sur un système indexé par 0. Le premier caractère est pair, avec l'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
MildlyMilquetoast
la source
6

C,  78  77 octets

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;}

Essayez-le en ligne!

C (gcc), 72 octets

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;}

Essayez-le en ligne!

Steadybox
la source
6

Wolfram Language (Mathematica) , 26 21 octets

10∣(2-9^Range@8).#&

Essayez-le en ligne!

Prend la saisie sous forme de liste de 8 chiffres.

Comment ça marche

2-9^Range@8est congru modulo 10 à 2-(-1)^Range@8, qui est {3,1,3,1,3,1,3,1}. Nous prenons le produit scalaire de cette liste avec l'entrée et vérifions si le résultat est divisible par 10.

Wolfram Language (Mathematica) , 33 octets et non en concurrence

Check[#~BarcodeImage~"EAN8";1,0]&

Essayez-le en ligne!

Prend l'entrée sous forme de chaîne. Renvoie 1les codes à barres valides et 0ceux non valides.

Comment ça marche

La meilleure chose que je puisse trouver dans la manière d'un intégré (puisque Mathematica est tout à propos de ceux-ci).

Le bit intérieur #~BarcodeImage~"EAN8";1, génère une image du code à barres EAN8, puis l’ignore complètement et s’évalue à 1. Toutefois, si le code à barres est invalide, BarcodeImageun avertissement est généré qui Checkrenvoie un 0 dans ce cas.

Misha Lavrov
la source
3
Faites-vous le calcul à la main parce qu'il est plus court ou parce que Wolfram n'a pas encore de fonction ValidateEAN8BarCode () quelque part dans sa bibliothèque standard?
Mark
1
@Mark Mathematica ne peut pas valider le code à barres directement, mais je viens de trouver BarcodeImagece qui génère l'image du code à barres et valide le code à barres dans le processus. Alors Check[#~BarcodeImage~"EAN8";0,1]<1&, ça marcherait (mais c'est plus long).
Misha Lavrov
5

Java 8, 58 56 55 octets

a->{int r=0,m=1;for(int i:a)r+=(m^=2)*i;return r%10<1;}

-2 octets indirectement grâce à @RickHitchcock , en utilisant (m=4-m)*iau lieu de l' m++%2*2*i+iavoir vu dans sa réponse JavaScript .
-1 octet indirectement grâce à @ETHProductions (et @RickHitchcock ), en utilisant à la (m^=2)*iplace de (m=4-m)*i.

Explication:

Essayez ici.

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
Kevin Cruijssen
la source
1
Vous pouvez enregistrer un autre octet avec une astuce @ETHProductions m'a montré: changer m=4-mà m^=2.
Rick Hitchcock
@RickHitchcock Ah, bien sûr .. J'utilise ^=1assez souvent dans les réponses lorsque je veux changer entre 0et 1. ^=2travaille dans ce cas pour changer entre 1et 3. Belle astuce, et merci pour le commentaire de le mentionner. :)
Kevin Cruijssen
4

05AB1E , 14 octets

θ¹¨3X‚7∍*O(T%Q

Essayez-le en ligne!

A besoin d’être en tête 0, prend une liste de chiffres.

Erik le golfeur
la source
Semble échouer 3100004(devrait être la vérité).
Zgarb
@Zgarb You're missing a 0 there.
Erik the Outgolfer
Oh, it takes a string? Okay then, my bad.
Zgarb
@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.
Erik the Outgolfer
@Mr.Xcoder The question isn't very clear on that, I'll add another code which does handle for that below.
Erik the Outgolfer
4

Pyth, 8 bytes

!es+*2%2

Verify all the test cases!

Pyth, 13 bytes

If we can assume the input always has exactly 8 digits:

!es.e*bhy%hk2

Verify all the test cases!


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.

Mr. Xcoder
la source
Seems to fail on 3100004 (should be truthy).
Zgarb
@Zgarb Wait should we do 3*3+1*1+0*3+... or 0*3+3*1+1*0..? I thought we are supposed to do the former
Mr. Xcoder
In the new spec, leading digits are added to ensure there are exactly 8 (if I understand correctly).
Zgarb
@Zgarb Ok, fixed.
Mr. Xcoder
4

Haskell, 40 38 bytes

a=3:1:a
f x=mod(sum$zipWith(*)a x)10<1

Try it online!

Takes input as a list of 8 integers. A practical example of using infinite lists.

Edit: Saved 2 bytes thanks to GolfWolf

butterdogs
la source
2
Using a recursive definition instead of cycle saves 2 bytes.
Cristian Lupascu
4

Retina, 23 22 bytes

-1 byte thanks to Martin Ender!

(.).
$1$1$&
.
$*
M`
1$

Try it online!

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.

Leo
la source
2
I think you can drop the . on the match stage and match 1$ at the end.
Martin Ender
@MartinEnder very nice, I'll do that, thanks!
Leo
3

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.

AdmBorkBork
la source
Seems to fail on 3100004 (should be truthy).
Zgarb
@Zgarb Works for me? Try it online!
AdmBorkBork
Ah ok, I tested it without the quotes.
Zgarb
@Zgarb Ah, yeah. Without the quotes, PowerShell will implicitly cast as an integer, stripping the leading zero(s).
AdmBorkBork
3

Jelly, 16 bytes

ż3,1ṁ$P€SN%⁵
Ṫ=Ç

Try it online!

takes input as a list of digits

HyperNeutrino
la source
Nitpick: your TIO timeouts. Also, 16 bytes.
Erik the Outgolfer
@EriktheOutgolfer Wait what how. It works when I put the D in the footer. And yay thanks! :D
HyperNeutrino
@EriktheOutgolfer Am I doing something wrong? Your 16-byter appears to be invalid?
HyperNeutrino
Maybe, it works kinda differently, but yours seems a bit invalid too...specifically I think the last line should be DµṪ=Ç.
Erik the Outgolfer
1
Seems to fail on 3100004 (should be truthy).
Zgarb
3

APL (Dyalog), 14 bytes

Equivalent with streetster's solution.

Full program body. Prompts for list of numbers from STDIN.

0=10|+/⎕×83 1

Try it online!

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]

?

Adám
la source
1
You mean APL can't do it in one character from something like Ancient Sumerian or Linear B?
Mark
train: 0=10|-/+2×+/
ngn
3

05AB1E, 9 bytes

3X‚7∍*OTÖ

Try it online!

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
kalsowerus
la source
Nice! First thing I thought was "extend to length" when I saw this, haven't used that one yet.
Magic Octopus Urn
31×S*OTÖ for 8 bytes. × just pushes 31 n number of times. When you multiply, it automatically drops the extra 31's.
Magic Octopus Urn
@MagicOctopusUrn That seems to fail on the 6th testcase 69165430 -> 1
kalsowerus
3

J, 17 bytes

-10 bytes thanks to cole

0=10|1#.(8$3 1)*]

Try it online!

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|{:+[:+/[:*/(7$3 1),:}:

Try it online!

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
Jonah
la source
0=10|1#.(8$3 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, so 0=10|1#.]*8$3 1 may work for 15 (I'd check on tio but it seems to be down?)
cole
@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.
Jonah
3

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

Try it online!

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.

  • f stores the last digit of x in s (s=x%10),

  • Then calculates the sum in c (for(i=c=0;x;x/=10)c+=(1+2*i++%4)*x;)

    • c is the sum, i is a counter

    • for each digit including the first, add 1+2*i%4 times the digit (x%10) to the checksum and increment i (the i++ in 3-2*i++%4)

      • 1+2*i%4 is 1 when i is even and 0 when i is 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).

pizzapants184
la source
I think (x%10) can just be x as you're taking c%10 later anyway. Also I think you can use i<8 and then just test whether c%10 is zero at the end.
Neil
@Neil Thanks! That got -10 bytes.
pizzapants184
In fact I think s is unnecessary: c;i;f(x){for(i=c=0;i<8;x/=10)c+=(1+2*i++%4)*x;return c%10<1;}
Neil
the tio link is 61 bytes but in the answer it's 72, also don't know why x=c%10<1 or c=c%10<1 instead of return c%10<1 still works
Nahuel Fouilleul
also i<8 can be replaced by x
Nahuel Fouilleul
3

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.

Micheal Johnson
la source
You can save two bytes by removing the {} after the for. Also, function submissions have to be reusable, so you need to initialize s inside the function (just change i;s=0; to i,s; and i=0; to i=s=0;).
Steadybox
@Steadybox How can I remove the curly brackets?
Micheal Johnson
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 as for(i=0;i<8;i++)s+=v[i]*3+v[++i];.
Steadybox
@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.
Micheal Johnson
In your true/false answer, instead of +3 by adding ==0 it can be +2 by using <1 instead. :)
Kevin Cruijssen
2

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

Alternatively, you can Try it online!

Mr. Xcoder
la source
2

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

try it online

Nahuel Fouilleul
la source
1
Had a little play with this and thought I'd share a useful trick: --$| toggles between 1 and 0 so you can use that instead of ++$i%2 for an alternating boolean! Also, all that matters is that the total ($s) matches /0$/, managed to get 33 bytes combining those changes with s///: Try it online! (-l is just for visibility)
Dom Hastings
yes i though to s/./(something with $&)/ge and to /0$/ match but not the two combined.
Nahuel Fouilleul
2

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.

Bolce Bussiere
la source
2

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

la source
2

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
DLosc
la source
2

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;}

Try it online!

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

Try it online!

A direct port of @Snowman's answer.

Ayb4btu
la source
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).
Kevin Cruijssen
1

MATLAB/Octave, 32 bytes

@(x)~mod(sum([2*x(1:2:7),x]),10)

Try it online!

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)~
  1. Odd digits (one indexed) are multiplied by 2.
  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.
  3. We do the sum which will also include the supplied checksum within our sum.
  4. 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.
  5. The result is inverted to get a logical output of true if valid.
Tom Carpenter
la source
1

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
Wernisch
la source
=MOD(SUM((A1:H1)+2*(A1+C1+E1+G1)),10)=0 this formula exist in Excel?
RosLuP
@RosLuP, not predefined, no. But Modulo, Sum, + etc do ;-)
Wernisch
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
RosLuP
@RosLuP, Apologies, missed the changed ()s in your comment.
Wernisch
Problem is how Excel interprets =(A1:H1): This is not handled as an array. Is invalid if placed in any column not in A-H range. 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!)
Wernisch
1

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}
displayname
la source
Nice! FWIW you don’t need map here at all: zip takes a block. You can save a couple more bytes by using $. instead of initializing s: ->n{n.zip([3,1]*4){|x,y|$.+=x*y};$.%10<1}
Jordan
1

TI-Basic (83 series), 18 bytes

not(fPart(.1sum(2Ans-Ans9^cumSum(binomcdf(7,0

Takes input as a list in Ans. Returns 1 for valid barcodes and 0 for invalid ones.

A port of my Mathematica answer. Includes screenshot, in lieu of an online testing environment:

barcode screenshot

Notable feature: binomcdf(7,0 is used to generate the list {1,1,1,1,1,1,1,1} (the list of probabilities that from 7 trials with success probability 0, there will be at most N successes, for N=0,1,...,7). Then, cumSum( turns this into {1,2,3,4,5,6,7,8}.

This is one byte shorter than using the seq( command, though historically the point was that it's also significantly faster.

Misha Lavrov
la source