Radice RTA (Reverse-Then-Add) di un numero


22

La sequenza reverse-then-add (RTA) è una sequenza ottenuta aggiungendo un numero al suo reverse e ripetendo il processo sul risultato. Per es.,

5+5=1010+01=1111+11=2222+22=44 ...

Pertanto, la sequenza RTA di 5 contiene 10, 11, 22, 44, 88, 176, ecc.

La radice RTA di un numero è il numero più piccolo che è uguale a n o dà il rilancio a n nella sua sequenza RTA.nnn

Ad esempio, 44 ​​si trova nella sequenza RTA di 5, 10, 11, 13, 22, 31, ecc. Di questi, 5 è il più piccolo, e quindi RTAroot (44) = 5.

72 non fa parte della sequenza RTA di alcun numero, quindi è considerata la propria radice RTA.

L'input è un numero intero positivo in un intervallo che la tua lingua può naturalmente gestire.

L'output è la radice RTA del numero specificato, come definito sopra.

Casi test

Input
Output

44
5

72
72

132
3

143
49

1111
1

999
999

OEIS correlato: A067031 . L'output sarà un numero da questa sequenza.

Risposte:


13

Perl 6 , 45 44 byte

->\a{first {a∈($_,{$_+.flip}...*>a)},1..a}

Provalo online!

Spiegazione:

->\a{                                    }  # Anonymous code block
->\a     # That takes a number a
     first  # Find the first element
                                     1..a  # In the range 1 to a
           {                       },    # Where
            a       # a is an element of
              (             ...   )  # A sequence defined by
               $_,  # The first element is the number we're checking
                  {$_+.flip}  # Each element is the previous element plus its reverse
                               *>$a  # The last element is larger than a

5
La sintassi con i puntini di sospensione del Perl 6 diventa più magica ogni volta che la incontro. Quella specifica di sequenza basata su lambda è un'idea così chiara!
Sundar - Ripristina Monica l'

@sundar, quella sintassi era in realtà uno dei motivi principali per cui sono arrivato a Perl 6. (e perché, dopo qualche tempo, è diventata la mia lingua preferita)
Ramillies,

7

Brachylog , 24 22 byte

{~{ℕ≤.&≜↔;?+}{|↰₁}|}ᶠ⌋
  • 2 byte grazie a Sundar notando che avevo un {{e}}

Spiegazione

                --  f(n):
                --      g(x):
 {              --          h(y):
  ~             --              get z where k(z) = y
   {            --              k(z):
    ℕ≤.         --                  z>=0 and z<=k(z) (constrain so it doesn't keep looking)
    &≜          --                  label input (avoiding infinite stuff)
      ↔;?+      --                  return z+reverse(z)
   }            --
    {           --                  
     |↰₁        --              return z and h(z) (as in returning either)
    }           --                  
  |             --          return h(x) or x (as in returning either)
 }              --
ᶠ               --      get all possible answers for g(n)
  ⌋             --      return smallest of them

scusate la spiegazione traballante, questa è la migliore che ho potuto inventare

Provalo online!


1
L'uso di {|↰₁}lì è semplice ma geniale. Buon lavoro!
Sundar - Ripristina Monica l'

5

Haskell , 59 57 byte

-2 byte grazie a user1472751 (usando un secondo untilinvece della comprensione dell'elenco & head)!

f n=until((n==).until(>=n)((+)<*>read.reverse.show))(+1)1

Provalo online!

Spiegazione

Questo valuterà Trueper qualsiasi radice RTA:

(n==) . until (n<=) ((+)<*>read.reverse.show)

Il termine (+)<*>read.reverse.showè una versione giocata a golf di

\r-> r + read (reverse $ show r)

che aggiunge un numero a se stesso invertito.

La funzione untilsi applica ripetutamente (+)<*>read.reverse.showfino a quando non supera il nostro obiettivo.

Concludendo tutto questo in un altro ancora che untilinizia con 1e aggiungendo 1 con(+1) troverai il primo RTA-root.

Se non esiste una radice RTA corretta n, alla fine arriviamo a ndove untilnon si applica la funzione da allora n<=n.


1
È possibile salvare 2 byte utilizzando anche untilper il ciclo esterno: TIO
user1472751

5

05AB1E , 7 byte

Utilizzando la nuova versione di 05AB1E (riscritta in elisir).

Codice

L.ΔλjÂ+

Provalo online!

Spiegazione

L           # Create the list [1, ..., input]
 .Δ         # Iterate over each value and return the first value that returns a truthy value for:
   λ        #   Where the base case is the current value, compute the following sequence:
     Â+     #   Pop a(n - 1) and bifurcate (duplicate and reverse duplicate) and sum them up.
            #   This gives us: a(0) = value, a(n) = a(n - 1) + reversed(a(n - 1))
    j       #   A λ-generator with the 'j' flag, which pops a value (in this case the input)
            #   and check whether the value exists in the sequence. Since these sequences will be 
            #   infinitely long, this will only work strictly non-decreasing lists.

Aspetta .. jha un significato speciale in un ambiente ricorsivo? Conoscevo solo il through e lo λstesso all'interno dell'ambiente ricorsivo. Ce ne sono altri oltre j? EDIT: Ah, vedo qualcosa £anche nel codice sorgente . Dove viene utilizzato?
Kevin Cruijssen,

1
@KevinCruijssen Sì, si tratta di flag utilizzati nell'ambiente ricorsivo. jessenzialmente controlla se il valore di input è nella sequenza. £si assicura che restituisca i primi n valori della sequenza (uguale a λ<...>}¹£).
Adnan,

3

Gelatina , 12 11 byte

ṚḌ+ƊС€œi¹Ḣ

9991111 scadono su TIO.

Grazie a @JonathanAllan per il golf off 1 byte!

Provalo online!

Come funziona

ṚḌ+ƊС€œi¹Ḣ  Main link. Argument: n

      €      Map the link to the left over [1, ..., n].
    С         For each k, call the link to the left n times. Return the array of k
               and the link's n return values.
   Ɗ           Combine the three links to the left into a monadic link. Argument: j
Ṛ                Promote j to its digit array and reverse it.
 Ḍ               Undecimal; convert the resulting digit array to integer.
  +              Add the result to j.
       œi¹   Find the first multindimensional index of n.
          Ḣ  Head; extract the first coordinate.

3

Rubino, 66 57 byte

f=->n{(1..n).map{|m|m+(m.digits*'').to_i==n ?f[m]:n}.min}

Provalo online!

Funzione ricorsiva che "annulla" ripetutamente l'operazione RTA fino ad arrivare a un numero che non può essere prodotto da essa, quindi restituisce il minimo.

Invece di usare filter, che è lungo, ho semplicemente mapsuperato l'intervallo da 1 al numero. Per ogni m in questo intervallo, se m + rev (m) è il numero, chiama la funzione ricorsivamente su m ; in caso contrario, restituisce n . Questo rimuove entrambi la necessità di a filtere ci dà un caso base di f (n) = n gratuitamente.

I punti salienti includono il salvataggio di un byte con Integer#digits:

m.to_s.reverse.to_i
(m.digits*'').to_i
eval(m.digits*'')

L'ultimo sarebbe un byte più breve, ma purtroppo, Ruby analizza i numeri che iniziano 0come ottali.



2

Pyth , 12 byte

fqQ.W<HQ+s_`

Dai un'occhiata a una suite di test!

Sorprendentemente veloce ed efficiente. Tutti i casi di test eseguiti contemporaneamente richiedono meno di 2 secondi.

Come funziona

fqQ.W<HQ+s_` – Full program. Q is the variable that represents the input.
f            – Find the first positive integer T that satisfies a function.
   .W        – Functional while. This is an operator that takes two functions A(H)
               and B(Z) and while A(H) is truthy, H = B(Z). Initial value T.
     <HQ     – First function, A(H) – Condition: H is strictly less than Q.
        +s_` – Second function, B(Z) – Modifier.
         s_` – Reverse the string representation of Z and treat it as an integer.
        +    – Add it to Z.
             – It should be noted that .W, functional while, returns the ending
               value only. In other words ".W<HQ+s_`" can be interpreted as
               "Starting with T, while the current value is less than Q, add it
               to its reverse, and yield the final value after the loop ends".
 qQ          – Check if the result equals Q.

2

05AB1E , 13 byte

LʒIFDÂ+})Iå}н

Provalo online!

Spiegazione

L               # push range [1 ... input]
 ʒ         }    # filter, keep elements that are true under:
  IF   }        # input times do:
    D           # duplicate
     Â+         # add current number and its reverse
        )       # wrap in a list
         Iå     # check if input is in the list
            н   # get the first (smallest) one

Inteligente! So che la mia versione da 21 byte era già troppo lunga (che ho giocato a 16 con lo stesso approccio), ma non riuscivo davvero a trovare un modo per farlo più breve. Non riesco a credere di non aver pensato di usare head dopo il filtro .. Ho continuato a provare a usare l'indice di loop + 1 o il global_counter..>.>
Kevin Cruijssen,

2

JavaScript (ES6), 61 byte

n=>(g=k=>k-n?g(k>n?++x:+[...k+''].reverse().join``+k):x)(x=1)

Provalo online!

Commentate

n =>                        // n = input
  (g = k =>                 // g() = recursive function taking k = current value
    k - n ?                 //   if k is not equal to n:
      g(                    //     do a recursive call:
        k > n ?             //       if k is greater than n:
          ++x               //         increment the RTA root x and restart from there
        :                   //       else (k is less than n):
          +[...k + '']      //         split k into a list of digit characters
          .reverse().join`` //         reverse, join and coerce it back to an integer
          + k               //         add k
      )                     //     end of recursive call
    :                       //   else (k = n):
      x                     //     success: return the RTA root
  )(x = 1)                  // initial call to g() with k = x = 1

2

05AB1E , 21 16 15 byte

G¼N¹FÂ+йQi¾q]¹

-1 byte grazie a @Emigna .

Provalo online.

Spiegazione:

G               # Loop `N` in the range [1, input):
 ¼              #  Increase the global_counter by 1 first every iteration (0 by default)
 N              #  Push `N` to the stack as starting value for the inner-loop
  ¹F            #  Inner loop an input amount of times
    Â           #   Bifurcate (short for Duplicate & Reverse) the current value
                #    i.e. 10 → 10 and '01'
     +          #   Add them together
                #    i.e. 10 and '01' → 11
      Ð         #   Triplicate that value
                #   (one for the check below; one for the next iteration)
       ¹Qi      #   If it's equal to the input:
          ¾     #    Push the global_counter
           q    #    And terminate the program
                #    (after which the global_counter is implicitly printed to STDOUT)
]               # After all loops, if nothing was output yet:
 ¹              # Output the input

Non è necessaria la stampa a causa della stampa implicita.
Emigna,

1

Carbone , 33 byte

Nθ≔⊗θηW›ηθ«≔L⊞OυωηW‹ηθ≧⁺I⮌Iηη»ILυ

Provalo online! Il collegamento è alla versione dettagliata del codice. Spiegazione:

Nθ

Ingresso q.

≔⊗θη

Assegnare 2q a h in modo che il ciclo inizi.

W›ηθ«

Ripeti mentre h>q:

≔L⊞Oυωη

invia una stringa null fittizia a u aumentando così la sua lunghezza e assegnando la lunghezza risultante a h;

W‹ηθ

ripetere mentre h<q:

≧⁺I⮌Iηη

aggiungi il contrario di h a h.

»ILυ

Stampa la lunghezza finale di u che è la radice desiderata.


1

MATL , 17 byte

`@G:"ttVPU+]vG-}@

Provalo online!

Spiegazione

`         % Do...while loop
  @       %   Push iteration index, k (starting at 1)
  G:"     %   Do as many times as the input
    tt    %     Duplicate twice
    VPU   %     To string, reverse, to number
    +     %     Add
  ]       %   End
  v       %   Concatenate all stack into a column vector. This vector contains
          %   a sufficient number of terms of k's RTA sequence
  G-      %   Subtract input. This is used as loop condition, which is falsy
          %   if some entry is zero, indicating that we have found the input
          %   in k's RTA sequence
}         % Finally (execute on loop exit)
  @       %   Push current k
          % End (implicit). Display (implicit)

1
Proprio come nota a margine, ho usato MATL per generare gli output del test case, usando questa versione a 31 byte: :!`tG=~yV2&PU*+tG>~*tXzG=A~]f1) provalo online!
Sundar - Ripristina Monica il

1

Java 8, 103 byte

n->{for(int i=0,j;;)for(j=++i;j<=n;j+=n.valueOf(new StringBuffer(j+"").reverse()+""))if(n==j)return i;}

Provalo online.

Spiegazione:

n->{                // Method with Integer as both parameter and return-type
  for(int i=0,j;;)  //  Infinite loop `i`, starting at 0
    for(j=++i;      //  Increase `i` by 1 first, and then set `j` to this new `i`
        j<=n        //  Inner loop as long as `j` is smaller than or equal to the input
        ;           //    After every iteration:
         j+=        //     Increase `j` by:
            n.valueOf(new StringBuffer(j+"").reverse()+""))
                    //     `j` reversed
     if(n==j)       //   If the input and `j` are equal:
       return i;}   //    Return `i` as result

L'inversione aritmetica dell'intero è più lunga di 1 byte ( 104 byte ):

n->{for(int i=0,j,t,r;;)for(j=++i;j<=n;){for(t=j,r=0;t>0;t/=10)r=r*10+t%10;if((j+=r)==n|i==n)return i;}}

Provalo online.


1

C (gcc) , 120 100 99 byte

f(i,o,a,b,c,d){for(a=o=i;b=a;o=i/b?a:o,a--)for(;b<i;b+=c)for(c=0,d=b;d;d/=10)c=c*10+d%10;return o;}

Provalo online!

Dato input i, controlla ogni numero intero da i0 a una sequenza contenente i.

  • i è il valore di input
  • o è il valore di output (la radice minima trovata finora)
  • a è il numero intero corrente da verificare
  • bè l'elemento corrente della asequenza di
  • ce dsono usati per aggiungere bal suo rovescio

Compilare con ti -DL=forfarebbe risparmiare 2 byte.

Grattalo; fare male la matematica.

Tuttavia, è possibile restituire il valore di output con i=o;se si utilizza -O0, risparmiando 5 byte.

1

Japt , 16 15 11 byte

@ÇX±swÃøU}a

Provalo

@ÇX±swÃøU}a     :Implicit input of integer U
@        }a     :Loop over the positive integers as X & output the first that returns true
 Ç              :  Map the range [0,U)
  X±            :    Increment X by
    sw          :    Its reverse
      Ã         :  End map
       øU       :  Contains U?


0

C (gcc) , 89 byte

Eseguo ciascuna sequenza in [1, n ) finché non ottengo una corrispondenza; zero ha un case speciale perché non termina.

j,k,l,m;r(i){for(j=k=0;k-i&&++j<i;)for(k=j;k<i;k+=m)for(l=k,m=0;l;l/=10)m=m*10+l%10;j=j;}

Provalo online!

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.