Palíndromos basados
Un número palindrómico, como recordatorio, es cualquier número que se lea igual hacia adelante que hacia atrás. Sin embargo, ¿qué pasa con los palíndromos en otras bases?
Entrada
Cualquier entero b
donde b > 1
.
Salida
Todos los números enteros en base 10 del 0 al 1000 inclusive que son palíndromos en la base b. La salida puede ser una lista de enteros o enteros separados por un delimitador, como una coma o una nueva línea.
Casos de prueba
Input->Output
10->{0,1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99,101,111,121,131,141,151,161,171,181,191,202,212,222,232,242,252,262,272,282,292,303,313,323,333,343,353,363,373,383,393,404,414,424,434,444,454,464,474,484,494,505,515,525,535,545,555,565,575,585,595,606,616,626,636,646,656,666,676,686,696,707,717,727,737,747,757,767,777,787,797,808,818,828,838,848,858,868,878,888,898,909,919,929,939,949,959,969,979,989,999}
2->{0,1,3,5,7,9,15,17,21,27,31,33,45,51,63,65,73,85,93,99,107,119,127,129,153,165,189,195,219,231,255,257,273,297,313,325,341,365,381,387,403,427,443,455,471,495,511,513,561,585,633,645,693,717,765,771,819,843,891,903,951,975}
9->{0,1,2,3,4,5,6,7,8,10,20,30,40,50,60,70,80,82,91,100,109,118,127,136,145,154,164,173,182,191,200,209,218,227,236,246,255,264,273,282,291,300,309,318,328,337,346,355,364,373,382,391,400,410,419,428,437,446,455,464,473,482,492,501,510,519,528,537,546,555,564,574,583,592,601,610,619,628,637,646,656,665,674,683,692,701,710,719,728,730,820,910,1000}
Respuestas
Python 3 , 78 bytes
Emite los números en orden decreciente 1000 -> 0
y los cortocircuitos con unZeroDivisionError
def f(b,n=1000):
r=0;m=n
while m:r=r*b+m%b;m//=b
n==r==print(n);f(b,n-n//n)
¡Pruébelo en línea!
Los f(b,n-n//n) -> f(b,n-1)
recurses hasta 0
y los errores porque dividir por cero no está definido.
Python 3 , 76 bytes
Podemos acortar la respuesta en 2 bytes si se permite una salida de punto flotante.
def f(b,n=1e3):
r=0;m=n
while m:r=r*b+m%b;m//=b
n==r==print(n);f(b,n-n/n)
¡Pruébelo en línea!
C (gcc) hacia delante, 118 117 115 bytes
b[11],*p,*x,i,m;f(n){for(i=-1;i++<1e3;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}
¡Pruébelo en línea!
C (gcc) , hacia atrás, 115 113 bytes
b[11],*p,*x,i,m;f(n){for(i=1001;i--;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}
¡Pruébelo en línea!
Explicación
Firma C:
// Technically implicit int with a void return
void f(int base);
Recorre todos los números del 0 al 1000, los convierte a la base base
a mano y luego comprueba si es un palíndromo.
La versión al revés hace lo mismo, pero al revés.
Imprime números coincidentes, separados por comas, en stdout.
Versión sin golf
#include <stdio.h>
// A buffer to hold our converted integer.
// It is large enough for 1000 in binary.
int buffer[11];
// Start and end pointers for buffer
int *start, *end;
// Loop counter
int i;
// Temporary
int tmp;
void f(int base)
{
// Loop for 0 to 1000
#ifdef BACKWARDS
// Loop backwards
for (i = 1001; i-- != 0;) {
#else
// Loop forwards
// for (i = 0; i <= 1000; i++)
for (i = -1; i++ < 1e3; ) {
#endif
// Convert to base in buffer, tracking the length in end.
for(start = end = buffer, tmp = i; tmp != 0;) {
*end++ = tmp % base;
tmp /= base;
}
// Check if it is a palindrome.
// Loop while our starting pointer is less than our ending pointer.
// tmp will zero at the start thanks to the loop condition.
while (end > start)
// Assembly style comparison using subtraction.
// If *end == *start, tmp will still be zero.
// If not, it will be permanently set to non-zero with a binary or.
tmp |= *--end - *start++;
// If tmp is still zero (meaning it is a palindrome), print.
tmp || printf("%d,", i);
}
}
¡Gracias a Arnauld por los -1 bytes!
¡Gracias a Toby Speight por los -2 bytes!
05AB1E , 7 bytes
₄ÝʒIвÂQ
¡Pruébelo en línea!
Explicado
₄Ý "Push the range [0, 1000]"\
ʒ "and keep the items where:"\
Iв "After being converted to base (input)"\
ÂQ "have its reverse equal to itself"\
Gelatina , 7 bytes
ȷŻbŒḂ¥Ƈ
¡Pruébelo en línea!
Cómo funciona
ȷŻbŒḂ¥Ƈ - Main link. Takes a base b on the left
ȷ - 1000
Ż - [0, 1, 2, ..., 1000]
¥ - Group the previous 2 links into a dyad f(k, b):
b - Convert k to base b
ŒḂ - Is this a palindrome?
Ƈ - Filter [0, 1, 2, ..., 1000], keeping those k that are true under f(k, b)
Japonés , 11 bytes
A³ô fÈìU êê
Intentalo
Wolfram Language (Mathematica) , 44 bytes
Pick[r=0~Range~1000,r-r~IntegerReverse~#,0]&
¡Pruébelo en línea!
-13 bytes de @att
JavaScript (ES6), 87 86 bytes
Devuelve una cadena separada por comas.
n=>(g=k=>--k&&g(k)+((h=k=>a=k?[k%n,...h(k/n|0)]:[])(k)+''==a.reverse()?[,k]:''))(1001)
¡Pruébelo en línea!
¿Cómo?
n => ( // n = input base
g = k => // g is a recursive function taking a counter k
--k && // decrement k; abort if it's equal to 0
g(k) + ( // otherwise do a recursive call and append the ...
( h = k => // ... result of the recursive function h
a = k ? // which builds an array a[]
[ k % n, // consisting of each digit of k in base n,
...h(k / n | 0) ] // dividing k by n and taking the integer part
: // for the next iteration until k = 0
[] //
)(k) + '' // invoke h with k and coerce the result to a string
== a.reverse() ? // if this is palindromic:
[, k] // append a comma followed by k to the output
: // else:
'' // just append an empty string
) //
)(1001) // initial call to g with k = 1001
Scala , 62 87 bytes
- Fija después de Siu Ching Pong -Asuka Kenji- señaló
BigInt
EstoString
sólo funciona para las bases hasta 36. - Ahorró 1 byte gracias a @cubic lettuce .
b=>0 to 1000 filter{x=>val y=Seq.unfold(x){q=>Option.when(q>0)(q%b,q/b)};y==y.reverse}
¡Pruébelo en línea!
Esto es bastante sencillo. Hace un rango de 0 a 1000, luego filtra comprobando si son iguales a su reverso en la base b
. Para convertir a la base b
(como una cadena), BigInt
's toString
método se ha utilizado, pero ahora Seq.unfold
se utiliza para crear una Seq
de dígitos.
Cáscara , 12 11 bytes
Editar: -1 byte gracias a LegionMammal978
foS=↔B⁰ŀdḋ9
¡Pruébelo en línea!
El código real 'palíndromo basado' es de 7 bytes ( foS=↔B⁰
), pero especificar 0 ... 1000 cuesta 5 4 (gracias a LegionMammal978) más bytes.
Podríamos guardar un byte si está bien generar algunos palíndromos más basados con valores hasta el decimal 1024 ( foS=↔B⁰ŀ□32
).
f # output the truthy values of
ŀdḋ9 # series from zero up to one less than 1001
# (decimal interpretation of binary digits of '9')
o # based on combination of 2 functions:
S=↔ # 1. is it equal to reverse of itself?
B⁰ # 2. digits in base given by argument
Carbón , 14 bytes
NθIΦ⊕φ⁼↨ιθ⮌↨ιθ
¡Pruébelo en línea! El enlace corresponde a una versión detallada del código. Explicación:
Nθ Input the base `b`
φ Predefined variable 1000
⊕ Incremented
Φ Filter on implicit range
ι Current value
↨ θ Converted to base `b`
⁼ Equals
ι Current value
↨ θ Converted to base `b`
⮌ Reversed
I Cast to string
Implicitly print
Haskell , 63 bytes
f b|let 0%m=m;n%m=div n b%(m*b+mod n b)=[n|n<-[0..1000],n==n%0]
¡Pruébelo en línea!
Basado en una buena idea de la respuesta de Python de dingledooper : para verificar que n
sea un b
palíndromo base , no genere la lista de b
dígitos base , sino invierta n
como b
número base ejecutando una conversión de base leyendo dígitos desde el final, y compruebe que el resultado sigue siendo igual n
.
El código |let 0%m=m;n%m=div n b%(m*b+mod n b)
define de forma recursiva una función infija %
que invierte la base n
(dada 0
como segundo argumento inicial). Definirlo dentro de un let
guard nos permite acceder al argumento b
de la función principal, mientras que una función independiente necesitaría seguir pasándolo con cada llamada recursiva.
APL (Dyalog extendido) , 17 15 bytes
¡Gracias a Razetime por -2 bytes!
¡Un error solucionado gracias a Siu Ching Pong !
Requiere origen de índice 0
.
⍸⎕(⊤≡∘⌽⊤)¨⍳1001
¡Pruébelo en línea!
⍝ tradfn taking the base as input
⍳1001 ⍝ the indices up to 1000
⍵( )¨ ⍝ apply a function to each index as a right argument and the input base as a left argument:
⌽⊤ ⍝ the reverse of the index converted to the input base
≡ ⍝ does it match
⊤ ⍝ the index converted to the input base
⍸ ⍝ all truthy indices
C - 76 bytes
i=1001,a,z;f(b){for(;i--;i-z||printf("%d ",i))for(a=i,z=0;a;a/=b)z=z*b+a%b;}
Explicación
Suficientemente diferente de mi respuesta anterior para justificar la publicación por separado. Esta vez, invertimos completamente el número y luego lo comparamos con el original. Por lo tanto, no es necesario eliminar los ceros finales o el caso especial 0
.
void fun(int b)
{
for (int i = 1001; i--;) {
int z = 0;
for (int a = i; a != 0; a /= b) {
z = z*b + a%b;
}
if (i==z) {
printf("%d ",i);
}
}
}
Este método funciona de manera confiable para i
hasta INT_MAX/b
y b
hasta INT_MAX
, o los equivalentes apropiados si cambiamos el tipo de entero utilizado. Para los tipos sin firmar (o con gcc -fwrapv
), debería funcionar para toda la gama de i
.
C, 100 bytes
i=1001,a,z;f(b){for(;--i;)for(a=i,z=0;i%b*a;a/=b)if(a==z||a==(z=z*b+a%b))printf("%d ",i);puts("0");}
Pruébelo en línea
Código sin golf
void fun(int b)
{
for (int i = 1001; --i;) {
if (i%b) { /* no leading/trailing zeros */
for (int a = i, z = 0; a != 0; a /= b) {
if (a==z) {
printf("%d ",i);
}
z = z*b + a%b;
if (a==z) {
printf("%d ",i);
}
}
}
}
puts("0");
}
Explicación
Esto genera los números más altos primero, ya que no se especificó ningún orden en particular. Para cada número candidato, lo reducimos (como a
) dividiéndolo sucesivamente por la base, usando el resto para construir el número inverso (en z
). Si se a
vuelve igual a z
, entonces tenemos un palíndromo. Por lo general, nos detendríamos allí ( a >= z
en la condición de bucle), pero para jugar al golf, continuamos hasta el final a==0
.
Necesitamos probar la igualdad antes y después de transferir el resto a z
, para aceptar palíndromos pares e impares.
Finalmente, imprimimos 0
, que siempre es un palíndromo, y es más fácil de incluir en casos especiales que en el bucle.
El método funciona para los números enteros hasta INT_MAX
si ungolf la condición i%b*a
de nuevo a i%b&&a
, y también funcionaría para otros tipos enteros.
K (ngn / k) , 18 bytes
{&{x~|x}'x\'!1001}
¡Pruébelo en línea!
x\'!1001
convertir cada uno de 0..1000 en representación base-x{x~|x}'
comprobar si cada representación es un palíndromo&
obtener índices de verdad
Python 3.8 (versión preliminar) , 92 85 bytes
lambda b:[i for i in range(1001)if(f:=lambda n:n*[0]and[n%b]+f(n//b))(i)==f(i)[::-1]]
¡Pruébelo en línea!
¡Gracias a dingledooper por ahorrar 7 bytes!
Haskell, 67 bytes
b&n=take n$mod n b:b&div n b
f b=[n|n<-[0..1000],reverse(b&n)==b&n]
f
es la función de interés. ¡Pruébelo en línea!
Quizás el único bit inteligente aquí es el uso de take n
para hacer un caso base para la función de expansión de dígitos. Cuando n=0
, take n
ignora su argumento y, por lo tanto, la recursividad se detiene por pereza; cuando n>0
, ciertamente no habrá más que n
dígitos, por lo que es seguro mantener solo el primero n
. La siguiente definición es equivalente (e igualmente larga):
b&0=[]
b&n=mod n b:b&div n b
... pero la take n
versión es más divertida porque es más confusa. ^ _ ^
J , 27 bytes
((-:|.)@(#.inv)"0#])i.@1001
Cómo
(...) i.@1001
- Todo es un gancho en J, lo que significa que el argumento será el argumento izquierdo para todo en los parens, y el argumento derecho serán los números enteros de 0 a 1000:i.@1001
...#]
La frase dentro del parens usa copy#
para filtrar el argumento derecho]
por la máscara booleana resultante de la frase a la izquierda de#
:(-:|.)@(#.inv)"0
- El rango 0"0
asegura que la frase se aplique a cada número individual del argumento correcto. La frase misma primero convierte cada uno de esos números en una lista de dígitos en la base dada por el argumento de la izquierda(#.inv)
, y luego verifica si esa lista es igual a su reverso(-:|.)@
. Por lo tanto, la frase completa devolverá 1 cuando esto sea cierto y 0 en caso contrario, y esta máscara booleana filtrará el argumento derecho como se desee.
¡Pruébelo en línea!
Ruby 2.7 , 74 bytes
->b{(0..1e3).select{(a=(g=->k,r=[]{k>0?g[k/b,r<<k%b]:r})[_1])==a.reverse}}
¡Pruébelo en línea!
TIO usa una versión anterior de Ruby, mientras que en Ruby 2.7, tenemos parámetros numerados, lo que ahorra dos bytes.
Rubí , 48 bytes
->b{(0..1e3).select{|k|(k=k.to_s b)==k.reverse}}
¡Pruébelo en línea!
No funciona para bases mayores de 64 debido a la limitación del .to_s
método.
JavaScript (V8) , 77 89 bytes
Fijo para bases mayores de 36.
b=>{for(i=-1;i<1e3;){j=[],k=++i;while(k|=0)j.push(k%b),k/=b;''+j==j.reverse()&&print(i)}}
¡Pruébelo en línea!
PowerShell ,
102
100
98
95
87
75 bytes
-14 bytes gracias a mazzy!
param($u)0..1e3|?{for($b=@();$_=($_-($b+=$_%$u)[-1])/$u){}"$b"-eq$b[11..0]}
¡Pruébelo en línea!
R , 82 81 bytes
(o 79 bytes usando el delimitador bastante complicado de " \n[1]
")
Editar: -1 byte gracias a caird coinheringaahing
function(b)for(i in 0:1e3)if(!i||all((a=i%/%b^(0:log(i,b))%%b)==rev(a)))cat(i,'')
¡Pruébelo en línea!
Calcula manualmente los dígitos en una nueva representación base y comprueba si son iguales a ellos mismos invertidos.
function(b)
for(i in 0:1000) # loop i through zero to 1000
if(!i # if i is zero (always a palindrome),
|| # or
all( # if all the digits of
(a=i%/%b^(0:log(i,b))%%b) # a = the representation of i in base b
==rev(a)) # are the same as themselves reversed
)cat(i,'') # output this i
jq , 66 bytes
. as$a|range(1001)|select([while(.>0;./$a|floor)|.%$a]|reverse==.)
¡Pruébelo en línea!
Explicación
. as $a | # Assign the input to $a. range(1001) | # For every item in [0..1000]: select ( # Filter out all items where: [ while(. > 0; # The list of quotients from repeatedly . / $a | floor) # short-dividing by $a |. % $a] # And then modulo-ing by $a
| reverse == .) # is equal to its reverse
```
Pyth , 11 bytes
f_IjTQUh^T3
¡Pruébelo en línea!
f_IjTQUh^T3 | Explanation
------------+---------------------------------------
f | filter
Uh^T3 | the range [0, 1001)
jTQ | on whether each number in base <input>
_I | equals itself reversed
Java 10, 118 bytes
b->{for(int i=-1;i++<1e3;){var s=b.toString(i,b);if(s.contains(new StringBuffer(s).reverse()))System.out.println(i);}}
Pruébelo en línea.
Explicación:
b->{ // Method with Integer parameter and no return-type
for(int i=-1;i++<1e3;){ // Loop `i` in the range [0,1000]:
var s=b.toString(i,b); // Convert `i` to base-`b` as String
if(s.contains(new StringBuffer(s).reverse()))
// If this String is a palindrome:
System.out.println(i);}} // Print `i` with trailing newline