Número de transformaciones hasta repetir

12

Dada una secuencia de enteros o, para ser más específicos, una permutación de 0..N transformar esta secuencia de la siguiente manera:

  • salida [x] = reversa (entrada [entrada [x]])
  • repetir

Por ejemplo: se [2,1,0]convierte [0,1,2]y se invierte es [2,1,0]. [0,2,1]se convierte [0,1,2]y se invierte [2,1,0].

Ejemplo 1

In:   0 1 2
S#1:  2 1 0
S#2:  2 1 0
Output: 1

Ejemplo 2

In:   2 1 0
S#1:  2 1 0
Output: 0

Ejemplo 3

In:   3 0 1 2
S#1:  1 0 3 2
S#2:  3 2 1 0
S#3:  3 2 1 0
Output: 2

Ejemplo 4

In:   3 0 2 1
S#1:  0 2 3 1
S#2:  2 1 3 0
S#3:  2 0 1 3
S#4:  3 0 2 1
Output: 3

Su tarea es definir una función (o programa) que tome una permutación de enteros 0..Ny devuelva (o produzca) el número de pasos hasta que ocurra una permutación que ya ha ocurrido. Si se Xtransforma a, Xentonces la salida debería ser cero, si se Xtransforma a Yy Yhacia X(o Y), entonces la salida debería ser 1.

Y -> Y: 0 steps
Y -> X -> X: 1 step
Y -> X -> Y: 1 step
A -> B -> C -> D -> C: 3 steps
A -> B -> C -> D -> A: 3 steps
A -> B -> C -> A: 2 steps
A -> B -> C -> C: 2 steps
A -> B -> C -> B: also 2 steps

Casos de prueba:

4 3 0 1 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps 
4 3 2 1 0 -> 4 3 2 1 0: 0 steps
4 3 1 2 0 -> 4 1 3 2 0 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps
1 2 3 0 4 -> 4 1 0 3 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 3 steps
5 1 2 3 0 4 -> 0 5 3 2 1 4 -> 1 5 3 2 4 0 -> 1 4 3 2 0 5 -> 
  5 1 3 2 0 4 -> 0 5 3 2 1 4: 4 steps

Si su idioma no admite "funciones", puede suponer que la secuencia se da como una lista separada de espacios enteros en blanco, como 0 1 2o 3 1 0 2en una sola línea.

Hechos graciosos:

  • la secuencia 0,1,2,3, .., N siempre se transformará en N, ..., 3,2,1,0
  • la secuencia N, .., 3,2,1,0 siempre se transformará en N, .., 3,2,1,0
  • la secuencia 0,1,3,2, ..., N + 1, N siempre se transformará en N, ..., 3,2,1,0

Tarea adicional : averiguar una fórmula matemática.

Reglas opcionales :

  • Si el primer índice de su idioma es 1 en lugar de 0, puede usar permutaciones 1..N(puede agregar uno a cada número entero en el ejemplo y en los casos de prueba).
mroman
fuente
Me refería más a una "fórmula cerrada" como $ f (a_ {0}, a_ {1}, a _ {...}} = a_ {0} ^ a_ {1} + ... $ donde $ a_ { i} $ es el elemento i-ésimo en la secuencia dada.
mroman
¿Estás seguro de que existe una "fórmula cerrada"?
Todd Sewell
" devuelve (o genera) el número de pasos hasta que se produce una permutación que ya ha ocurrido " . Esto es inconsistente con casi todo lo que le sigue. Para empezar, hace imposible un valor de retorno de 0 ...
Peter Taylor
¿Es correcto el tercer ejemplo? Veo 3,0,1,2debe transformar a2,3,0,1
FireCubez
Es el número de transformaciones antes de una repetición.
mroman

Respuestas:

4

JavaScript (ES6), 54 bytes

a=>~(g=a=>g[a]||~-g(g[a]=a.map(i=>a[i]).reverse()))(a)

Pruébalo en línea!

Arnauld
fuente
¿Qué hace []en una función?
mroman
Una función es un objeto. Por lo tanto, g[a]se puede utilizar para acceder a la propiedad a.
Arnauld
Ah, ya veo. Estás usando gpara almacenar el estado en.
mroman
3

Pyth, 10 9 8 bytes

tl.u@LN_

Explicación:

t               One less than
 l              the number of values achieved by
  .u            repeating the following lambda N until already seen value:
    @LN_N         composing permutation N with its reverse
         Q      starting with the input.

Banco de pruebas .

lirtosiast
fuente
3

Haskell, 52 bytes

([]#)
a#x|elem x a= -1|n<-x:a=1+n#reverse(map(x!!)x)

Pruébalo en línea!

a # x                -- function '#' takes a list of all permutations
                     -- seen so far (-> 'a') and the current p. (-> 'x')
  | elem x a = -1    -- if x has been seen before, return -1 
  | n<-x:a =         -- else let 'n' be the new list of seen p.s and return
    1 +              -- 1 plus
       n #           -- a recursive call of '#' with the 'n' and
        reverse ...  -- the new p.

([]#)                -- start with an empty list of seen p.s 
nimi
fuente
3

Perl 6 , 44 35 bytes

-9 bytes gracias a nwellnhof

{($_,{.[[R,] |$_]}...{%.{$_}++})-2}

Pruébalo en línea!

Explicación:

{                              }  # Anonymous code block
                  ...    # Create a sequence where:
  $_,  # The first element is the input list
     {.[[R,] |$_]} # Subsequent elements are the previous element reverse indexed into itself
                     {        }    # Until
                      %.{$_}       # The index of the listt in an anonymous hash is non-zero
                            ++     # Then post increment it
 (                            )-2  # Return the length of the sequence minus 2
Jo King
fuente
2

J, 33 27 26 bytes

-7 gracias a bubbler

_1(+~:i.0:)|.@C.~^:(<@!@#)

Pruébalo en línea!

cómo

explicación original mi última mejora solo cambia la pieza que encuentra "el índice del primer elemento que ya hemos visto". ahora usa el "tamiz de nubes" para hacerlo en menos bytes.

1 <:@i.~ [: ({: e. }:)\ |.@C.~^:(<@!@#)
                        |.@C.~          NB. self-apply permutation and reverse
                              ^:        NB. this many times:
                                (<@!@#) NB. the box of the factorial of the
                                        NB. the list len.  this guarantees
                                        NB. we terminate, and the box means
                                        NB. we collect all the results
         [: ({: e. }:)\                 NB. apply this to those results:
                      \                 NB. for each prefix
             {: e. }:                   NB. is the last item contained in 
                                        NB. the list of previous items?
1 <:@i.~                                NB. in that result find:
1    i.~                                NB. the index of the first 1
  <:@                                   NB. and subtract 1

Tenga en cuenta que toda la frase final 1<:@i.~[:({:e.}:)\está dedicada a encontrar "el índice del primer elemento que ya se ha visto". Esto parece terriblemente largo para obtener eso, pero no pude jugar más al golf. Sugerencias de bienvenida.

Jonás
fuente