Введение:
Голландский BSN (BurgerServiceNummer) действителен, если он соответствует следующим правилам:
- Он содержит только цифры.
- Длина должна быть 8 или 9 в длину.
- Когда цифры индексируются как
A
сквозныеI
, результат следующей суммы:9xA + 8xB + 7xC + 6xD + 5xE + 4xF + 3xG + 2xH + -1xI
(ЗАМЕТЬТЕ -1 вместо 1!) Должен делиться на 11 и не должен быть 0.
Вызов:
Вход: строка или массив символов, представляющий BSN.
Выход: truthy или falsey результат вход является ли действительным BSN.
Правила соревнований:
- Формат ввода должен быть строкой или массивом символов. Вы не можете использовать int-массив цифр или (возможно, восьмеричное) число. (Вы можете преобразовать его в массив цифр int самостоятельно, но не в качестве аргумента.)
- Несмотря на ограничение на вводимые выше данные, можно предположить, что все тестовые случаи будут содержать одну или несколько цифр (
[0-9]+
) - Что касается BSN с длиной 8 вместо 9, голландская Википедия заявляет следующее: « Для теста с одиннадцатью и для других практических целей добавляется начальный ноль, чтобы сделать число длиной 9 ». ( Источник )
Основные правила:
- Это код-гольф , поэтому выигрывает самый короткий ответ в байтах.
Не позволяйте языкам кода-гольфа отговаривать вас от публикации ответов на языках, не относящихся к кодексу. Попробуйте придумать как можно более короткий ответ для «любого» языка программирования. - К вашему ответу применяются стандартные правила , поэтому вы можете использовать STDIN / STDOUT, функции / метод с правильными параметрами, полные программы. Ваш звонок.
- По умолчанию лазейки запрещены.
- Если возможно, добавьте ссылку с тестом для вашего кода.
- Также, пожалуйста, добавьте объяснение, если это необходимо.
Тестовые случаи:
// Truthy test cases:
111222333
123456782
232262536
010464554
10464554
44016773
// Falsey test cases:
000000000
192837465
247594057
88888888
73
3112223342
000000012
code-golf
string
arithmetic
decision-problem
Кевин Круйссен
источник
источник
A
из приведенной формулы?A
из формулы (или, по сути, добавляет ведущий,0
чтобы сделать его длиной 9, что приводит к тому же результату, что и пропускA
).Ответы:
05AB1E,
2321 bytesTry it online! or as a Test suite
Explanation
источник
DgL
toā
and0Ê
toĀ
. Try it online.JavaScript (ES6) 57
Input as an array of chars.
reduceRight
saves the day!Test
источник
reduceRight
answer!map()
, just to realize that your answer is actually 57 bytes long :-)R,
8667 bytesEdit: Thanks to Jarko Dubbeldam for suggesting the dot product!
Reads input from stdin and store as an array/vector of characters. Subsequently convert to numeric,multiply with the vector
9...2,-1
and check all conditions.источник
x
as vector.if(l<9)x=c(0,x);s=sum(as.double(x)*c(9:2,-1))
can be turned intos=sum(as.double(x)*c(l:2,-1))
. Also, the sum of the pairwise product of two vectors is the same as their dot-multiplication%*%
.JavaScript (ES6),
61605958 bytesTakes an array of chars as input. Returns
false
/true
.Test cases
Show code snippet
источник
C,
1121019698104 bytesThanks to @MartinEnder for saving
53 byteswhile fixing my code!Returns 0 if invalid, 1 if valid. Try it online!
источник
61
even though it is not of correct length.R,
957993 bytesUnnamed function that takes a string as argument. At first I overread the requirement of having a string as input instead of a number, but that's good, because it saves some bytes on conversion.
I am not sure how to interpret the array of characters, but if that means that you can use a vector of stringed digits
"1" "2" "3" "4" etc
as input, it becomes a bit shorter even:Splits x into a numeric vector, then appends a 0 if length is 8, then calculates the dotproduct of vector y and
c(9,8,7,6,5,4,3,2,-1)
. Tests if the result is both nonzero and divisible by 11.Saved 16 bytes thanks to the logic by @Enigma, implicitly appending the 0 in the creation of the vector
c(length(x):2,-1)
.Forgot to add check for length 8/9, so +14 bytes :(
источник
Perl, 58 bytes (52 + 6)
Run with
Input passed through
STDIN
:Usage
Outputs
1
for as the truthy value,0
or nothing for falsey values.источник
$r+=$_*(-1,2..9)[$i++]for reverse@F
. Also,-F -pe
(and input supplied without final newline, withecho -n
for instance) is enough (unless your Perl is too old, in which case you'll need-a
(but on recent Perls, it's implied by-F
). Finally, your code was 70 bytes long, not 52 ;)C++14,
107106 bytes-1 byte for
int
instead ofauto
in for loop.As unnamed lambda returning via reference parameter. Requires input to be
std::string
or a container of char, likevector<char>
.Ungolfed and usage:
источник
Befunge, 72 bytes
Try it online!
Explanation
источник
MATL, 36 bytes
Not the longest MATL program I've ever written, but I like how
if
/else
statements get very lengthy very quickly in golfing languages. I feel that this solution may not be optimal in MATL, but as of yet I can't optimize it any further. I'm thinking of using the double 0 somewhere, and maybe cut down on thet
's everywhere.Try it online! Explanation:
источник
!U
instead of48-
[a2:9]*
results in a non-element-wise multiplication, so another!
would be needed which would offset the initial gain.MATL, 26 bytes
The result is a non-empty column vector, which is truthy iff all its entries are nonzero.
Try it online!
Or verify all test cases with each result on a different line.
Explanation
This tests the three conditions in the following order:
Consider input
'8925'
for the explanation.;
is the row separator for matrices.источник
?
would probably be more efficient, but I couldn't figure out how to shorten the length 8 or 9. YourGn8-tg=
is very clever.!
?G
pushes a column vector and I need to transpose it to do the repetition withg*
Haskell,
116112102 bytesg
counts the sum used in the eleven-proef ofh
, whilef
also checks for the correct length and that the eleven-proef is not 0. Especially the checks off
take a lot of bytes.EDIT: saved 10 bytes thanks to Lynn and
div
rounding down.источник
f x=div(length x)2==4&&g x>0&&h x
?Jelly, 21 bytes
TryItOnline! or run all test cases
Truthy return values are non-zero (and are, in fact, the multiple of 11 sum).
How?
источник
Python 2, 102 bytes
источник
Python 2, 96 bytes
Takes a string as input. The function adds a
'0'
to the front of the string whether it needs it or not, and uses Python's negative indices to add elements, starting from the end of the string and working back-to-front.The
-1xI
is handled separately, using a second call toint()
. I couldn't figure out how to avoid this without costing more bytes than I saved.def g(s):u=7<len(s)<10and sum(x*int(('0'+s)[-x])for x in range(10))-2*int(s[-1]);print(u%11<1)*u
would work just as well, since it would add1
timess[-1]
but then subtract it twice, and it would also add0
times (something) which of course wouldn't affect the sum.источник
Brain-Flak, 345 Bytes
Includes +3 for
-a
Truthy is 1, Falsy has a 0 on the top of the stack.
Try it Online!
I'm pretty sure there is a shorter way to do the multiplication in a loop, but I haven't found it yet.
источник
PowerShell v2+, 96 bytes
OK, I'll admit, this looks like a complete mess. And it kinda is. But, bear with me and we'll get through it.
We take input
$n
(as achar
-array) and set$i
equal to8
minus a Boolean value for whether there are 8 items in$n
. Meaning, if there are 8 items, then$i
would be7
.The next section combines the calculation with our output. Working from the inside, we loop through
$n
with$n|%{...}
. Each iteration, we use a pseudo-ternary to come up with one of two results -- either-"$_"
or(($i+1)*+"$_")
. The index is based on whether$i
is0
or not (i.e., we've hit the-1xI
case from the challenge equation), which gets post-decremented for the next go-round. Those are all gathered up in parens and-join
ed together with+
. For example, with input111222333
at this point we'd have9+8+7+12+10+8+9+6+-3
. That is piped toiex
(short forInvoke-Expression
and similar toeval
) before being stored into$b
. We then take that%11
and perform a Boolean-not!(...)
on that (i.e., so if it is divisible by 11, this portion is$true
). That's coupled with-and$b
to ensure that$b
is non-zero. That Boolean result is left on the pipeline and output is implicit.Examples
источник
PHP
139128 bytesCould not get the CLI to just echo the true of false. Had to make do it this way. Any ideas?
128 bytes: Turned "true" and "false" to 1 and 0.
источник
C#,
120115 bytesThis loops through the
char[]
it receives as input and returns true or false:Fiddle: https://dotnetfiddle.net/3Kaxrt
I'm sure I can scrape out a few bytes, especially in the messy
return
. Any ideas welcome!Edit: Saved 5 bytes thanks to Kevin. I had no idea I could use
&
instead of&&
!источник
r>0&&r%11==0&&l<10&&l>7
can be golfed tor>0&r%11<1&l<10&l>7
(&&
to&
andr%11==0
tor%11<1
). And-'0'
can be golfed to-48
.PHP,
868584838279 bytesNote: uses PHP 7.1 for negative string indices.
Run like this:
Version for PHP < 7.1 (+10 bytes)
Explanation
Tweaks
"0"
, saved a byte10000000
is invalid, no need to compare withgreater than or equals
,greater than
suffices, saving a byte-R
to make$argn
availableисточник
Java 8,
11598 bytesI'm surprised no one has posted a Java answer yet, so here is one.
Explanation:
Try it here.
источник
Clojure, 114 bytes
Well this is something,
-
substracts the rest of the arguments from the first one so that handles the special case of weight-1
. This function returnsnil
for inputs of invalid length, but onif
clauses they operate the same asfalse
.(#{8 9}(count v))
returnsnil
if length ofv
is not 8 or 9.Test cases:
источник
Perl 5, 63 + 2 (
-F
) = 65 bytesTry it online!
источник
Stax, 23 bytes
Run and debug online!
Explanation
Uses the unpacked version to explain.
источник