Palíndromos Baseados

Dec 28 2020

Um número palíndromo, como um lembrete, é qualquer número que tenha a mesma leitura para frente ou para trás. Porém, e os palíndromos em outras bases?

Entrada

Qualquer número inteiro bonde b > 1.

Resultado

Todos os números inteiros de base 10 de 0 a 1000 inclusive que são palíndromos na base b. A saída pode ser uma lista de inteiros ou inteiros separados por um delimitador, como uma vírgula ou uma nova linha.

Casos de teste

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}

Respostas

12 dingledooper Dec 29 2020 at 03:01

Python 3 , 78 bytes

Exibe os números em ordem decrescente 1000 -> 0e provoca curto-circuitos com umZeroDivisionError

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)

Experimente online!

O f(b,n-n//n) -> f(b,n-1)recorre até 0e erros porque a divisão por zero é indefinida.

Python 3 , 76 bytes

Podemos encurtar a resposta em 2 bytes se uma saída de ponto flutuante for permitida.

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)

Experimente online!

10 EasyasPi Dec 28 2020 at 13:02

C (gcc) para a frente, 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);}}

Experimente online!

C (gcc) , para trá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);}}

Experimente online!

Explicação

Assinatura C:

// Technically implicit int with a void return
void f(int base);

Faz um loop por todos os números de 0 a 1000, converte-os em uma base basemanualmente e verifica se é um palíndromo.

A versão reversa faz a mesma coisa, mas ao contrário.

Imprime números correspondentes, separados por vírgula, em stdout.

Versão sem golfe

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

Obrigado a Arnauld pelos -1 bytes!

Obrigado a Toby Speight pelos -2 bytes!

10 Lyxal Dec 28 2020 at 04:54

05AB1E , 7 bytes

₄ÝʒIвÂQ

Experimente online!

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"\
6 cairdcoinheringaahing Dec 28 2020 at 04:42

Jelly , 7 bytes

ȷŻbŒḂ¥Ƈ

Experimente online!

Como 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)
6 Shaggy Dec 28 2020 at 07:48

Japt , 11 bytes

A³ô fÈìU êê

Tente

6 J42161217 Dec 28 2020 at 04:53

Linguagem Wolfram (Mathematica) , 44 bytes

Pick[r=0~Range~1000,r-r~IntegerReverse~#,0]&

Experimente online!

-13 bytes de @att

6 Arnauld Dec 28 2020 at 07:35

JavaScript (ES6),  87  86 bytes

Retorna uma string separada por vírgulas.

n=>(g=k=>--k&&g(k)+((h=k=>a=k?[k%n,...h(k/n|0)]:[])(k)+''==a.reverse()?[,k]:''))(1001)

Experimente online!

Como?

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
6 user Dec 28 2020 at 05:16

Scala , 62 87 bytes

  • Fixado após Siu Ching Pong -Asuka Kenji- apontado BigInté toStringsó funciona para bases até 36.
  • 1 byte salvo graças à alface @cubic .
b=>0 to 1000 filter{x=>val y=Seq.unfold(x){q=>Option.when(q>0)(q%b,q/b)};y==y.reverse}

Experimente online!

Isso é muito simples. Ele faz um intervalo de 0 a 1000, então filtra verificando se eles são iguais ao reverso na base b. Para converter a base de b(como uma cadeia), BigIntde toStringmétodo é foi usado, mas agora Seq.unfoldé usada para criar um Seqde dígitos.

6 DominicvanEssen Dec 28 2020 at 08:04

Husk , 12 11 bytes

Editar: -1 byte graças a LegionMammal978

foS=↔B⁰ŀdḋ9

Experimente online!

O código real do 'palíndromo baseado' tem 7 bytes ( foS=↔B⁰), mas especificar 0 ... 1000 custa 5 4 (graças ao LegionMammal978) a mais bytes.
Poderíamos salvar um byte se estiver tudo bem para produzir mais alguns palíndromos baseados com valores até o 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
5 Neil Dec 28 2020 at 05:33

Carvão , 14 bytes

NθIΦ⊕φ⁼↨ιθ⮌↨ιθ

Experimente online! O link é para a versão detalhada do código. Explicação:

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
5 xnor Dec 29 2020 at 10:59

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]

Experimente online!

Com base em uma boa ideia da resposta Python de dingledooper : para verificar se né um bpalíndromo de base , não gere a lista de bdígitos de base , mas inverta ncomo um bnúmero de base executando uma conversão de base lendo dígitos a partir do final, e verifique se o resultado ainda é igual n.

O código |let 0%m=m;n%m=div n b%(m*b+mod n b)define recursivamente uma função infixo %que inverte a base n(fornecida 0como um segundo argumento inicial). Defini-lo dentro de um letguarda nos permite acessar o argumento bpara a função principal, enquanto uma função autônoma precisaria continuar transmitindo-o a cada chamada recursiva.

5 ovs Dec 28 2020 at 19:02

APL (Dyalog Extended) , 17 15 bytes

Graças a Razetime por -2 bytes!
Um bug corrigido graças a Siu Ching Pong !

Requer origem do índice 0.

⍸⎕(⊤≡∘⌽⊤)¨⍳1001

Experimente online!

                 ⍝ 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
5 TobySpeight Dec 29 2020 at 00:06

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

Explicação

Suficientemente diferente da minha resposta anterior para justificar a postagem separadamente. Desta vez, invertemos completamente o número e, em seguida, comparamos com o original. Portanto, não precisamos eliminar zeros à direita ou casos especiais 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 forma confiável para iaté INT_MAX/be baté INT_MAX, ou os equivalentes apropriados, se alterarmos o tipo de inteiro usado. Para tipos não assinados (ou com gcc -fwrapv), deve funcionar para toda a gama de i.

4 TobySpeight Dec 28 2020 at 23:28

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

Experimente online

Código não-golfe

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

Explicação

Isso gera os números mais altos primeiro, uma vez que nenhuma ordem particular foi especificada. Para cada número candidato, nós o reduzimos (as a) dividindo sucessivamente pela base, usando o resto para construir o número reverso (in z). Se afor igual a z, então temos um palíndromo. Normalmente, pararíamos por aí ( a >= zna condição de loop), mas para o golfe, continuamos até a==0.

Precisamos testar a igualdade antes e depois de transferir o restante para z, para aceitar palíndromos de comprimento ímpar e par.

Por fim, imprimimos 0, que é sempre um palíndromo, e é mais fácil criar um caso especial do que incluir no loop.

O método funciona para inteiros até INT_MAXse desfazermos a condição de i%b*avolta i%b&&a, e também funcionaria para outros tipos de inteiros.

4 coltim Dec 28 2020 at 23:57

K (ngn / k) , 18 bytes

{&{x~|x}'x\'!1001}

Experimente online!

  • x\'!1001 converter cada um de 0..1000 para representação de base x
  • {x~|x}' verifique se cada representação é um palíndromo
  • & obter índices de verdadeiros
4 Danis Dec 28 2020 at 12:59

Python 3.8 (pré-lançamento) , 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]]

Experimente online!

Graças a dingledooper por economizar 7 bytes!

4 DanielWagner Dec 29 2020 at 01:45

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é a função de interesse. Experimente online!

Talvez a única coisa inteligente aqui seja o uso de take npara fazer um caso base para a função de expansão de dígitos. Quando n=0, take nignora seu argumento e a recursão para por preguiça; quando n>0, certamente não haverá mais do que ndígitos, então é seguro manter apenas o primeiro n. A seguinte definição é equivalente (e igualmente longa):

b&0=[]
b&n=mod n b:b&div n b

... mas a take nversão é mais divertida porque é mais confusa. ^ _ ^

4 Jonah Dec 28 2020 at 13:16

J , 27 bytes

((-:|.)@(#.inv)"0#])i.@1001

Como

  • (...) i.@1001 - A coisa toda é um gancho J, o que significa que o argumento será o argumento esquerdo para tudo nos parênteses, e o argumento direito serão os inteiros de 0 a 1000: i.@1001
  • ...#]A frase dentro dos parênteses usa cópia #para filtrar o argumento direito ]pela máscara booleana resultante da frase à esquerda de #:
  • (-:|.)@(#.inv)"0- A classificação 0 "0garante que a frase se aplica a cada número individual do argumento correto. A própria frase primeiro converte cada um desses números em uma lista de dígitos na base fornecida pelo arg à esquerda (#.inv)e, em seguida, verifica se essa lista é igual ao reverso (-:|.)@. A frase inteira, portanto, retornará 1 quando isso for verdadeiro e 0 caso contrário, e essa máscara booleana filtrará o argumento correto conforme desejado.

Experimente online!

3 vrintle Dec 28 2020 at 11:13

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

Experimente online!

TIO usa uma versão mais antiga do Ruby, enquanto que no Ruby 2.7, numeramos os parâmetros, o que economiza dois bytes.


Ruby , 48 bytes

->b{(0..1e3).select{|k|(k=k.to_s b)==k.reverse}}

Experimente online!

Não funciona para bases acima de 64, devido à limitação do .to_smétodo.

3 NinaLisitsinskaya Dec 29 2020 at 02:07

JavaScript (V8) , 77 89 bytes

Fixo para bases maiores que 36.

b=>{for(i=-1;i<1e3;){j=[],k=++i;while(k|=0)j.push(k%b),k/=b;''+j==j.reverse()&&print(i)}}

Experimente online!

3 ZaelinGoodman Dec 29 2020 at 03:26

PowerShell , 102 100 98 95 87 75 bytes

-14 bytes graças ao mazzy!

param($u)0..1e3|?{for($b=@();$_=($_-($b+=$_%$u)[-1])/$u){}"$b"-eq$b[11..0]}

Experimente online!

2 DominicvanEssen Dec 28 2020 at 19:44

R , 82 81 bytes

(ou 79 bytes usando o delimitador bastante complicado de " \n[1] ")

Edit: -1 byte graças 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,'')

Experimente online!

Calcula manualmente os dígitos na nova representação da base e verifica se eles são iguais ao contrário.

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
1 2x-1 Jan 03 2021 at 10:09

jq , 66 bytes

. as$a|range(1001)|select([while(.>0;./$a|floor)|.%$a]|reverse==.)

Experimente online!

Explicação

. 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
```
1 hakr14 Jan 03 2021 at 10:47

Pyth , 11 bytes

f_IjTQUh^T3

Experimente online!


f_IjTQUh^T3 | Explanation
------------+---------------------------------------
f           | filter
      Uh^T3 | the range [0, 1001)
   jTQ      | on whether each number in base <input>
 _I         | equals itself reversed
1 KevinCruijssen Jan 07 2021 at 15:21

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

Experimente online.

Explicação:

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