Contraer enteros consecutivos


22

Relacionado: ¡ Dime cuántos problemas matemáticos tengo que hacer!

Reto

Dada una lista entera estrictamente positiva estrictamente ascendente L y un número entero 3 ≤ N ≤ longitud de L, reemplace los enteros medios de las series enteras consecutivas de L de longitud ≥ N con un solo guión -.

Reglas

  • El espacio en blanco horizontal es irrelevante.
  • Opcionalmente, puede conservar los caracteres de introducción, separación y terminación del formato de lista predeterminado de su idioma. Ver ejemplos de formatos , a continuación.

Ejemplos de datos

Todos estos ejemplos usan L = 3 5 6 7 8 10 11 12 14 16 17 18 19 20 21 22 24.

N = 3 → 3 5 - 8 10 - 12 14 16 - 22 24

N = 4 → 3 5 - 8 10 11 12 14 16 - 22 24

N = 5 → 3 5 6 7 8 10 11 12 14 16 - 22 24

N = 8 → 3 5 6 7 8 10 11 12 14 16 17 18 19 20 21 22 24

Ejemplos de formato

Para las entradas
 L = [3,5,6,7,8,10,11,12,14,16,17,18,19,20,21,22,24]y N = 3
todas las líneas a continuación hay ejemplos de respuestas válidas, tanto como listas reales como cadenas:

[3,5,"-",8,10,"-",12,14,16,"-",22,24]
[3,5,-,8,10,-,12,14,16,-,22,24]
[3,5-8,10-12,14,16-22,24]
3,5-8,10-12,14,16-22,24

Lo mismo se aplica con otros formatos de lista, como {1 2 3}y (1; 2; 3)etc. ¿Tiene dudas? ¡Pedir!


¿Es necesario usar -o se nos permite usar un símbolo diferente?
— millas

@miles ¿Un símbolo diferente le ahorrará bytes?
— Adám

Estoy pensando en usar infinito _para poder seguir operando en matrices numéricas en J.
— millas

@miles Ah, sí, ¿por qué no sigues adelante y haces eso, pero no te preocupes por eso, y si puedes molestarte, escribe la solución en caja (supongo que mucho más tiempo) '-'? También es posible que pueda clasificar todo antes de insertar guiones, ¿no?
— Adám

¿Es válido lo siguiente? [3,5,-8,10,-12,14,16,-22,24](este parece ser el formato que tiene más sentido en términos de tipos)
— Leaky Nun

Respuestas:



6

Jalea ,  26 25  23 bytes

-2 bytes gracias a Erik the Outgolfer (al traer la declaración if al enlace principal)

Ḣ;Ṫj”-
IỊ¬1;œṗ⁸¹ÇL<¥?€F

Un enlace diádico que devuelve una lista en el [3,5,"-",8,10,"-",12,14,16,"-",22,24]formato.

Pruébalo en línea! (el pie de página se separa con espacios, para imprimir el formato de ejemplo de datos).

¿Cómo?

Ḣ;Ṫj”- - Link 1, format a run: list R
Ḣ      -     head
  Ṫ    -     tail
 ;     -     concatenate
    ”- -     literal '-'
   j   -     join

IỊ¬1;œṗ⁸¹ÇL<¥?€F - Main link: list L, number N
I                - incremental differences
 Ị               - insignificant? (<=1)
  ¬              - not
   1;            - prepend a 1
       ⁸         - chain's left argument, L
     œṗ          - partition (L) at truthy indexes
              €  - for €ach row, R, in L:
             ?   -   if:
            ¥    -   condition: last two links as a dyad:
          L      -     length of R
           <     -     is less than N?
        ¹        -   then: identity - do nothing, yields R
         Ç       -   else: call the last link (1) as a monad with argument  R
               F - flatten into a single list

¿Un enlace monádico?
— Leaky Nun

je, y uno "especial" en eso.
— Jonathan Allan


Buenas cosas, gracias @EriktheOutgolfer!
— Jonathan Allan

4

Pyth, 23 bytes

sm?<ldvzd[hd\-ed).ga=hZ

Pruébalo en línea

Cómo funciona

sm?<ldvzd[hd\-ed).ga=hZkQ

                        Q    autoinitialized to eval(input())
                 .g          group by k ↦
                    =hZ          Z += 1, returning new value (Z is autoinitialized to 0)
                   a   k         absolute difference with k
 m                           map d ↦
  ?                              if
    ld                               length of d
   <  vz                             less than eval(z) (z is autoinitialized to input())
        d                        then d
         [hd\-ed)                else [d[0], '-', d[-1]]
s                            concatenate

3

Japt , 24 bytes

óÈÄ¥Yîl ¨V?Zv +'-+Zo :Z

Pruébalo en línea!

Explicación

óÈ   Ä ¥ YÃ ®   l ¨ V?Zv +'-+Zo :Z
óXY{X+1==Y} mZ{Zl >=V?Zv +'-+Zo :Z}   Ungolfed
                                      Implicit: U = input array, V = input integer
óXY{      }                           Group U into runs such that for each pair X, Y:
    X+1==Y                              Y is exactly 1 more than X.
            mZ{                   }   Map each run Z to:
               Zl >=V?                  If Z has at least V items:
                      Zv     Zo           Z.unshift() and Z.pop() (the first and last items)
                         +'-+             joined with a hyphen.
                                :       Otherwise:
                                 Z        just Z.
                                      Implicit: output result of last expression

2

Mathematica, 128 bytes

(s=#2;t=r=1;While[t<Length@s,If[s[[t+1]]-s[[t]]==1,r++,r=1];If[r==#,s[[t-#+3;;t]]="-";r--];t++];s//.{b___,a_,a_,c___}:>{b,a,c})&


entrada

[3, {3,5,6,7,8,10,11,12,14,16,17,18,19,20,21,22,24}]

salida

{3, 5, "-", 8, 10, "-", 12, 14, 16, "-", 22, 24}

Pruébalo en línea!



2

APL, 38 bytes

{∊⍺{⍺>≢⍵:⍵⋄2⌽'-',2↑¯1⌽⍵}¨⍵⊂⍨1,1≠2-⍨/⍵}

1

PHP 7, 1371361341171010108 bytes

for($a=$argv,$i=2;$n=$a[$i++];$k<$a[1]||array_splice($a,$i,$k-2,"-"))for($k=print"$n ";$a[$i+$k]-++$k==$n;);

Toma Ldel primer argumento, enumere los elementos después de eso. Ejecutar -nro probarlo en línea .

Reemplace $L=($a=$argv)con $a=$argv,$L=(+1 byte) para PHP <7.

Descompostura

for($a=$argv,$i=2;              # import input
    $n=$a[$i++];                # loop $n through list elements
    $k<$a[1]||                      # 3. if streak length ($k) is >=L ($a[1])
        array_splice($a,$i,$k-2,"-")    # then replace with "-"
)
for($k=print"$n ";                  # 1. print element and space
    $a[$i+$k]-++$k==$n;);           # 2. find consecutive numbers

1

Retina , 101 bytes

\d+
$*
\b(1+) (?=1\1\b)
$1X
T`X` `\b((X)|1)+\b(?=.*¶(?<-2>1)+(?(2)(?!))11)
T`X`-
-1+(?=-)|¶1+

1+
$.&

Pruébalo en línea! Toma la lista separada por espacios Len la primera línea y el número entero Nen la segunda línea. Explicación: La primera etapa convierte la entrada a unario. La segunda etapa cambia el espacio entre enteros consecutivos a an X. La tercera etapa busca corridas de enteros consecutivos cuya longitud es menor Ny Xvuelve a cambiar sus espacios a espacios. La cuarta etapa cambia la Xs a -(esto fue 3 bytes más corto que usar -s en primer lugar). La quinta etapa elimina todos los enteros que aún quedan en el medio de una ejecución, así como N, mientras que la etapa final se convierte de nuevo a decimal.


1

Ruby, 68 bytes

->n,l{l.slice_when{|x,y|x<y-1}.map{|x|x[n-1]?x.minmax.uniq*?-:x}*?,}

Devuelve una cadena como por ejemplo 3,5-8,10-12,14,16-22,24.

Pruébalo en línea!


1

J , 40 bytes

;@((](,_,{:)/)^:(<:#)&.>]<;.1~1,1<}.-}:)

Pruébalo en línea!

Usos en _lugar de -.

Explicación

;@((](,_,{:)/)^:(<:#)&.>]<;.1~1,1<}.-}:)  Input: integer N (LHS), array L (RHS)
                                  }.      Behead L
                                     }:   Curtail L
                                    -     Subtract elementwise to get the increments
                                1<        Test if greater than 1
                              1,          Prepend a 1
                        ]                 Get L
                         <;.1~            Partition L into boxes using the previous array
                     & >                  Operate on each box (partition) with N
              ^:                            If
                   #                          The length of the partition
                 <:                           Is greater than or equal to N
   (](     )/)                                Reduce (right-to-left) it using
         {:                                     Tail
       _,                                       Prepend _
      ,                                         Append to LHS
                     &.>                    Box the result
;@                                        Raze - join the contents in each box

0

Gelatina, 39 37 36 bytes

IỊṣ0;€1ṁ@
ÇL€<Ɠ¬TịÇḊ€Ṗ€F;€”-FyµŒgQ€F

Pruébalo en línea

Toma la matriz a través de argumentos, y el entero a través de STDIN. El enlace TIO utiliza el pie de página, ÇGpor lo que la salida está separada por espacios.

¿Cómo? (Array: a, Integer: n)

(`f`)
IỊṣ0;€1ṁ@
I          Deltas of `a`
 Ị         Insignificant (x -> abs(x)<=1) applied to each element
  ṣ0       Split at occurrences of `0`.
    ;€1    Append `1` to each element
       ṁ@  `a` shaped like that
ÇL€<Ɠ¬TịÇḊ€Ṗ€F;€”-FyµŒgQ€F
Ç                            `f`
 L€                          Length of each element
   <Ɠ                        x -> x < n applied to each element
     ¬                       Logical not of each element (because Jelly doesn't have <= nor >= atoms)
      T                      Nonzero indexes
       ịÇ                    Index `f` at those indexes
         Ḋ€Ṗ€                x -> x[1:-1] applied to each element
             F               Flatten
              ;€”-           Append a hyphen to each element
                  F          Flatten
                   y         Translate (replaces all elements to be deleted with a hyphen)
                    µ        Start a new monadic link
                     Œg      Group runs of equal elements
                       Q€    Uniquify each element (make runs of hyphens one hypen)
                         F   Flatten, yet again.

Supongo que me caí ... de plano en este caso.


0

JavaScript (ES6), 126 119 bytes

(e,c)=>{for(i=0,R='';i<e.length;R+=(R&&',')+(u-m>=c?m+'-'+--u:e.slice(z,i))){m=u=e[i],z=i;while(e[++i]==++u);}return R}

Una función anónima. Toma la entrada en el orden Array L, Integer Ny devuelve el resultado como una cadena separada por comas.


Usa el curry para guardar un byte e=>c=>.
— TheLethalCoder

0

Dyalog APL v16.0, 82 80 78 76 75 65 62 bytes

{S/⍨1,⍨2≠/S←'-'@(⍸⊃∨/(-0,⍳⍺-3)⌽¨⊂(⍴⍵)↑∧/¨(⍺-1),/¯1⌽1=-2-/⍵)⊢⍵}

Wow, esto es ... malo. Probablemente haya una solución mucho más corta con stencil.

Pruébalo en línea!

Sugerencias de golf bienvenidas!


Si, que hay de eso?
— Zacharý

Lo siento, lugar equivocado.
— Adám

^ ¿Qué quieres decir?
— Zacharý

Mi comentario se basó en un desafío diferente.
— Adám

Supongo que si tiene una solución, Adám, ¿entonces utiliza v16 incorporadas?
— Zacharý
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.