(Nota: Este es un spin-off de mi desafío anterior ¡ Encuentra las palabras remolinadas! )
Definición de la palabra infinito :
- Si conecta con curvas todos los caracteres de una Palabra de infinito en el alfabeto (AZ), obtiene el símbolo de infinito ∞ como en los diagramas a continuación.
- Toda la conexión par debe estar inactiva , todas las conexiones impares deben estar activadas .
- Puede ignorar mayúsculas / minúsculas o considerar / convertir todo a mayúsculas o todo a minúsculas.
- Las palabras de entrada son solo caracteres en el rango alfabético de AZ, sin espacios, sin signos de puntuación o símbolos.
- Cada palabra debe tener exactamente 5 caracteres. Las palabras> 5 o <5 no son válidas.
- Si una palabra tiene caracteres dobles consecutivos, la palabra no es válida, como "INUNDACIÓN" o "REINA".
- Todas las palabras infinitas comienzan y terminan con el mismo personaje.
Aquí hay algunos ejemplos:
Tarea:
Escriba un programa o función completa que tomará una palabra de la entrada estándar y dará salida si es una palabra infinita o no. El resultado puede ser verdadero / falso, 1/0, 1 / nulo, etc.
Casos de prueba:
Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW
NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO
Reglas:
- El código más corto gana.
Tarea opcional:
Encuentre, como una lista, tantas palabras infinitas como pueda en un diccionario de inglés. Puede tomar como referencia la lista completa de palabras en inglés aquí .
Respuestas:
Jelly,
43 41 40 25 24 23 22 21 1413 bytes-7 bytes thanks to fireflame241 (
0ị=1ị$
->=ṚḢ
and use ofIIA⁼2,2
to test for the 4 rotations)-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad
Ø2
which yields[2,2]
)TryItOnline
Or all test cases (plus "RULES")
How?
An infinity word has:
All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of
[1,1,-1,-1]
(where the sign of0
is0
)fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in
[[2,2],[2,-2],[-2,2],[-2,-2]]
which may be tested by the absolute values being equal to[2,2]
!How?
fuente
II
to check for equality to a rotation of 1,1,-1,-1.Java 8,
23119318512210378 bytesTry it here.
-38 bytes thanks to @dpa97 for reminding me to use
char[]
instead ofString
.-63 bytes thanks to @KarlNapf's derived formula.
-25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer).
193 bytes answer:
Explanation:
false
false
true
if it complies to any of them (andfalse
otherwise):1<2<3>4>5
(i.e.ALPHA
)1>2<3<4>5
(i.e.EAGLE
,HARSH
,NINON
,PINUP
)1<2>3>4<5
(i.e.RULER
)1>2>3<4<5
(i.e.THEFT
,WIDOW
)These four rules can be simplified to
1*3<0 and 2*4<0
(thanks to @KarlNapf's Python 2 answer).fuente
char[]
as input instead ofString
. -38 bytes thanks to you.z,x
andw,y
must have an alternating sign, so it suffices to checkz*x<0
andw*y<0
JavaScript (ES6),
918987 bytesSaved 2 bytes thanks to Ismael Miguel
How it works
We build a 4-bit bitmask
k
representing the 4 transitions between the 5 characters of the string:NaN
so that the word is rejected (to comply with rule #6)The valid bitmasks are the ones that have exactly two consecutive
1
transitions (the first and the last bits being considered as consecutive as well):In other words, these are the combinations which are:
k?
: greater than 0!(k%3)
: congruent to 0 modulo 3The other conditions are:
!s[5]
: there's no more than 5 characterss[0]==s[4]
: the 1st and the 5th characters are identicalNB: We don't explicitly check
k != 15
because any word following such a pattern will be rejected by this last condition.Test cases
Show code snippet
Initial version
For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters.
Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well:
Edit: See Neil's answer for the fixed/completed version of the above code.
fuente
0000
is also congruent to 0 modulo 3 but again you can't have the first and last letters the same, so, like 15, you don't need to explicitly test for it.!((a>b)-(b>c)+(c>d)-(d>e))
?p<c?0:NaN
can be written as0/(p<c)
, which saves 2 bytes.k?
test because of the possibleNaN
.) Regarding your alternate version: that should work indeed.JavaScript (ES6), 78 bytes
Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart.
Edit: Alternative 78-byte solution based on @KarlNapf's answer:
fuente
Python 2 exit code, 56 bytes
Outputs via exit code: Error for False, and successful run for True.
Takes the string
s
with charactersabcde
, rotates it tobcdea
, does an elementwise comparison of corresponding characters, and assigns them to five variablesv,w,x,y,z
. The wrong length gives an error.The infinity words all have
which can be checked jointly as
v*x+w*y|z == -2
. The chained comparisonv*x+w*y|z>-2>_
short-circuits if this is the case, and otherwise goes on to evaluate-2>_
which gives a name error.fuente
Python 2,
1108760 bytesSaving 1 byte thanks to Neil
Requires input enclosed in quotes, e.g.
'KNEES'
True
if it is an infinity word,False
if not and it has length of 5 and prints error message if wrong lengthInspired by xnor's answer using
map(cmp...
previous solution:
Using the optimized logic of Kevin Cruijssen
fuente
a*c+b*d+2==0==e
?a*c+b*d|e
is even shorter.<-1
might work, since both-2|1
and-2|-1
equal-1
.PHP, 102 Bytes
fuente
Python 2, 71 bytes
Takes the string
s
with charactersabcde
, rotates it tobcdea
, and does an elementwise comparison of corresponding characters.The result is a list of
-1, 0, 1
. Then, checks if the result is one of the valid sequences of up and downs:as generated from the template
[m,n,-m,-n,0]
withm,n=±1
. The last0
checks that the first and last letter were equal, and the length ensures that the input string had length 5.An alternative 71. Checks the conditions on comparisons while ensuring the right length.
fuente
R, 144 bytes
The answer is based off the logic of @Jonathan Allan. It could probably be golfed though.
R-fiddle test cases (vectorized example but same logic)
fuente
length(s)==5
, you can replaces[1]==tail(s,1)
withs[1]==s[5]
. A one-byte shorter method to check the length isis.na(s[6])
. Together these two changes returnTRUE
fors
of length 5 exactly andFALSE
otherwise, asTRUE&NA
isNA
butFALSE&NA
isFALSE
. You can also save a few bytes by replacing!sum(sign(d))&any(rle(sign(d))$l>1)
with!sum(a<-sign(d))&any(rle(a)$l>1)
.GNU Prolog, 47 bytes
Defines a predicate
i
which succeeds (infinitely many times, in fact) for an infinity word, thus outputting "yes" when run from the interpreter (as is usual for Prolog); fails for a candidate word whose first and last letters don't match, or isn't 5 letters long, thus outputting "no" when run from the interpreter; and crashes with a stack overflow if given a candidate word that isn't an infinity word, but which is five letters with the first and last two matching. (I'm not sure why it crashes; the recursive call should be treatable as a tailcall. Apparently GNU Prolog's optimizer isn't very good.) Succeeding is Prolog's equivalent of truthy, and failing the equivalent of falsey; a crash is definitely more falsey than truthy, and fixing it would make the solution substantially longer, so I hope this counts as a valid solution.The algorithm is fairly simple (and indeed, the program is fairly readable); check whether the letters form one of the four patterns that make an infinity word, and if not, cyclicly permute and try again. We don't need to explicitly check for double letters as the
<
and>
operators let us implicitly check that at the same time that we check that the deltas match.fuente
Actually,
3827 bytesThis answer was largely inspired by Jonathan Allan's excellent Jelly answer. There are probably several places where this can be golfed, so golfing suggestions welcome! Try it online!
Ungolfing
fuente
APL (Dyalog),
1615 bytesTry it online!
fuente
TI-BASIC, 81 bytes
String to pass into the program is in Ans. Returns (and implicitly displays) 1 if the entered word is an Infinity Word, and 0 (or exits with an error message) if it isn't.
Errors on any repeated characters, or non-5-letter-words.
fuente
05AB1E, 16 bytes
Port of @JonathanAllan's Jelly answer.
Try it online or verify all test cases.
Explanation:
fuente