Para dígitos diferentes de zero em um teclado padrão
789
456
123
considere colocar um cavaleiro do xadrez em qualquer dígito e movê-lo com qualquer número de saltos normais em forma de L, traçando um número inteiro decimal positivo. Quais números inteiros positivos podem ser expressos dessa maneira?
Uma delas é 38
, já que o cavaleiro poderia começar 3
e se mover para a esquerda e para cima 8
. 381
e 383
também são possíveis.
3
em si é possível se nenhum salto for dado (o que é permitido). 5
também, mas nenhum outro dígito pode ser alcançado a partir do 5
, portanto, é o único número em que o dígito 5
aparece.
Escreva um programa ou função que receba um número inteiro decimal positivo (você pode tomá-lo como uma string, se desejar) e imprima ou retorne um valor verdadeiro se o número puder ser expresso por um cavaleiro em um teclado numérico da maneira descrita, mas, caso contrário, gera um valor falso .
O código mais curto em bytes vence. Desempate é resposta anterior
Exemplos
Verdade:
1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
Falsy:
10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
78963214
, repetidas vezes sem conta. Conte as distâncias - sempre são quatro, de um jeito ou de outro. Eu deveria ter sido mais claro e dito explicitamente que você deve escrevê-lo em ordem circular.123...9
. DesculpeRespostas:
Geléia,
191514 bytesExperimente online! ou verifique todos os casos de teste .
Como funciona
fonte
Python 2, 52 bytes
Verifica se há dois dígitos consecutivos na sequência
'18349276167294381'
. Para obter dígitos consecutivos, em vez de fazê-lozip(`n`,`n`[1:])
, a função verifica repetidamente os dois últimos dígitos e remove o último dígito.fonte
Retina ,
5840 bytesAgradecemos ao Sp3000 por sugerir esta idéia:
Experimente online! (Ligeiramente modificado para executar todo o conjunto de testes de uma vez.)
Imprime
1
para verdade e0
para resultados falsos.Explicação
Encontre todas as correspondências sobrepostas de
..
, ou seja, todos os pares consecutivos de dígitos, e junte-as a feeds de linha.Sort the digits in each line, so that we only need to check half as many pairs.
Remove all lines which correspond to a valid move.
Count the matches of this regex. That is, if all lines were removed, this matches the resulting empty string once, otherwise it fails to match and gives zero instead.
fonte
Pyth -
3528 bytesTest Suite.
fonte
Ruby, 57 bytes
Anonymous function. Argument is a string.
Program with the test suite:
I just encoded all the possible knight moves into a string and checked if every 2 digits within the input existed in that string.
fonte
grep 58 bytes
Because really, if you cannot beat grep...
fonte
5
nor185
emit1
with your command line, while5
is in the truthy, and185
in the falsy list.Haskell 46 bytes
Usage example:
all(`elem`q"16729438183492761").q $ "183492761"
->True
How it works: It uses the lookup string found in @Kevin Lau's answer.
q
makes a list of pairs of adjacent chars from a string, e.g.q "1672" -> [('1','6'),('6','7'),('7','2')]
. The function returns true if all pairs from the input appear in the pairs from the lookup string.q
turns single digit inputs into the empty list, soelem
always succeeds.fonte
zip<*>tail
work like a flipped version ofzip=<<tail
? I think I don't understand what applicatives generalize.<*>
is defined as(<*>) f g x = f x (g x)
.JavaScript (ES6),
6562 bytesReturns true or false. I'd previously tried a recursive solution, which takes 63 bytes, and
map
and evenreduce
but they took me 73 bytes.Edit: Saved 3 bytes thanks to @user81655.
fonte
match
works instead of~search
(but either way, that's really underhanded) and|
can replace||
(but not in the recursive version, sadly.)!i|...match
works because the match result, if successful, is an array of a single string of two digits, which the|
operator ends up coercing into a valid integer.C,
8581 bytesGolfed:
Old non-recursive version (85 bytes):
Old code with white-space and main program:
This accepts space-delimited numbers via standard input and outputs 0 if not-numpad-knight, or 1 otherwise.
The new 81-byte recursive version shaves 4 bytes.
fonte
MATL,
383729 bytesThis uses @QPaysTaxes idea.
The output is a 2D, complex, non-empty array. It is truthy if all its values have nonzero real part, and falsy otherwise.
Try it online!
fonte
05AB1E, 29 bytes
Code:
Uses CP-1252 encoding. Try it online!.
fonte
MATL,
25243326 bytesShaved off 1 byte thanks to @LuisMendo!
@Dennis found a bug, and then fixed it! Thanks!
Takes integer as input. Outputs 1/0.
Try it online!
fonte
A
at the end. MATL's vectors are truthy iff they do not contain a 0.C,
14092 bytesAssuming ASCII
Detailed Try it here
fonte
{,}[]
and encode it as achar*
string instead. Also, note that your#define
is not being cost-effective when you use it only twice: removing it would save you 4 bytes.\0
within the array caused undefined behavior so I replaced it withx
<s>oldscore</s> newscore
when editing to reflect score improvements, and<!-- language-all: lang-c -->
before your code starts to fix syntax highlighting. I also managed to reduce my byte-count somewhat by dropping the loop altogethern
in the short version?). Also, you probably ought to mention that you're assuming ASCII encoding - you'll get different numbers on EBCDIC machines.Julia,
5149 bytesVerification
fonte
Actually, 30 bytes
Takes input as a string. Outputs a positive integer for true and 0 for false.
Try it online!
Explanation:
fonte
PowerShell v2+,
10596 bytesIterates through the input (which must be encapsulated with
""
) by verifying that the index of any sequential pair of characters is in the valid lookup string. I see Kevin Lau had something similar, but I came up with this independently. Each of those indices are added with+1
, as the.IndexOf()
function will return-1
if the string isn't found. This will turn "not found"s into0
.We then
-join
all the resultant integer values with*
and pipe that toiex
(similar toeval
). This will mean if any one of the indices is not found, the entire expression will result in0
. That is encapsulated in parens and-or
'd with$a-eq5
for the special case of input"5"
to achieve our resultant output.Test Runs
fonte
C, 78 bytes
Since everyone else has taken the input as a string, I tried doing it in integers. It works recursively from the least-significant digit (
a%10
); if it's the only digit, then return true. Otherwise, return true only if the tens digit (b%10
) can't be reached from the units digit, and (recursively), the rest of the input satisfies the same test.The test for reachability works by encoding the knight's tour linearly, and converting each digit to its position (zero to seven) on the tour. For digits
0
and5
, we assign position nine, which is disconnected from the other positions. Then, mutually reachable numbers differ by one (mod eight); i.e.a[x%10]-a[b%10]
is either ±1 or ±7. So we test the absolute difference (mod 6) against 1.This solution works for any character encoding that is valid for C (i.e. digits have contiguous codes from 0 to 9).
fonte
Java 8,
179167 BytesPlaces the number pad ints (minus 5 and 0) in a circle.
l
holds the circle index of these ints. If the difference of two indices is +/- 3 mod 8, then there is a knights move between the ints corresponding to those indices. Note thatx
is anint[]
.Update
<2
instead of==1
fonte