El primero, el último y todo lo que hay entre


33

Dados dos enteros, genera los dos enteros y luego el rango entre ellos (excluyendo ambos).

El orden del rango debe ser el mismo que el de la entrada.

Ejemplos:

 Input        Output
 0,  5   ->   [0, 5, 1, 2, 3, 4]
-3,  8   ->   [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
 4,  4   ->   [4, 4]
 4,  5   ->   [4, 5]
 8,  2   ->   [8, 2, 7, 6, 5, 4, 3]
-2, -7   ->   [-2, -7, -3, -4, -5, -6]

¿Supongo que no podemos tomar las entradas en orden pre ordenado?
— Kevin Cruijssen

@KevinCruijssen, no, el orden de salida depende del orden de entrada
— TFeld

@StewieGriffin, el orden de salida debe ser el mismo que el de entrada
— TFeld

¿Es aceptable este formato de salida? Tenga en cuenta la nueva línea
— Luis Mendo

2
@KevinCruijssen Cualquier E / S razonable es aceptable.
— TFeld

Respuestas:


14

R , 39 33 30 bytes

c(a<-scan(),setdiff(a:a[2],a))

Pruébalo en línea!

Gracias por los bytes guardados para user2390246 y J.Doe.


Puede guardar algunos bytes tomando la entrada como un vector en lugar de como dos enteros separados.
— usuario2390246

Sí, eso es razonable, y en realidad se vuelve aún más corto como un programa completo en lugar de funcionar.
— Kirill L.

Puede abusar del hecho de que el :operador usa el primer elemento de ambos argumentos para 30 bytes
— J.Doe




8

Perl 6 , 26 22 bytes

{|@_,|[...^](@_).skip}

Pruébalo en línea!

Explicación

{                    }
 |@_,   # Slip args a,b into result
      [...^](@_)  # Reduce args a,b with ...^ operator, same as a...^b
                .skip  # Skip first element
     |  # Slip into result

7

Python 2 , 40 bytes

lambda x,y:[x,y]+range(x,y,-(y<x)|1)[1:]

Pruébalo en línea!


Realmente me gusta -(y<x)|1. muy bueno pero no puedo entender por qué funciona! ¿Alguna posibilidad de que puedas explicarlo?
— ElPedro

2
@ElPedro Básicamente, y<xcomprueba si yes estrictamente menor que x, y devuelve Truesi es así, de lo Falsecontrario. Después de eso, unarios -se aplica a ella, que convierte Truea -1y Falsea 0. El último paso es bit a bit O este número con 1. Esto obviamente deja 1( 0b1) sin afectar, y también deja -1( -0b1) sin afectar (el bit de signo de -1se establece, por lo que se mantiene como tal). Sin embargo, se convierte 0a 1, por lo que rangeno se queja de que yo use un stepde 0.
— Erik the Outgolfer

Eso es realmente genial y muy inteligente. Si pudiera votar dos veces, lo haría. Muchas gracias por la explicación.
— ElPedro


6

Japt, 8 bytes

cUr!õ kU

Pruébalo aquí

             :Implicit input of array U
c            :Concatenate
 Ur          :  Reduce U by
   !õ        :   Inclusive range
      kU     :  Remove all elements in original U

6

JavaScript (ES6), 51 bytes

Toma entrada como (a)(b).

a=>g=(b,c=b)=>(b+=b<a|-(b>a))-a?[...g(b,c),b]:[a,c]

Pruébalo en línea!

Comentado

a =>                // main function, taking a
  g = (             // g = recursive function
    b,              //     taking b
    c = b           // we save a backup of the original value of b into c
  ) =>              //
    (b +=           // add to b:
      b < a |       //   +1 if b is less than a
      -(b > a)      //   -1 if b is greater than a
    )               //   (or 0 if b = a)
    - a ?           // if the updated value of b is not equal to a:
      [             //   generate a new array:
        ...g(b, c), //     prepend all values generated by a recursive call
        b           //     append the current value of b
      ]             //
    :               // else:
      [a, c]        //   stop recursion and return the first 2 values: a and c

6

Python 2 , 47 41 40 bytes

lambda a,b:[a,b]+range(a,b,a<b or-1)[1:]

Pruébalo en línea!

Aquí está la mía, ahora que se han publicado muchas otras respuestas de Python

-6 bytes, gracias a GB


Aprovechar el rango vacío cuando no es válido es una forma inteligente de lidiar con listas hacia adelante o hacia atrás. Pude ver que es muy útil y es un buen truco saber que existe.
— akozi

2
41 bytes usando un solo rango: rango (a, b, (a <b) * 2-1)
— GB

a<b or-1es más corto para el tercer parámetro del rango. Lo más corto que obtuve fuelambda x,y:[x,y]+range(x+(x<y or-1),y,x<y or-1)
— mbomb007

5

Java 10, 109 108 104 102 93 62 bytes

Usando una cadena delimitada por espacios:

b->a->{var r=a+" "+b;for(;a<b?++a<b:--a>b;)r+=" "+a;return r;}

Pruébalo en línea.

Usando una lista:

b->a->{var r=new java.util.Stack();for(r.add(a),r.add(b);a<b?++a<b:--a>b;)r.add(a);return r;}

Pruébalo en línea.

( a<b?++a<b:--a>bpuede ser ++a<b||(a-=2)>bpara el mismo conteo de bytes: Pruébelo en línea para la Cadena o Pruébelo en línea para la Lista ).


Respuesta anterior ( 109 108 104 102 101 bytes) usando una matriz:

a->b->{int s=a<b?1:-1,i=a!=b?(b-a)*s+1:2,r[]=new int[i];for(r[0]=a,r[1]=b;i>2;)r[--i]=b-=s;return r;}

-7 bytes gracias a @nwellnhof .

Pruébalo en línea.

Explicación:

a->b->{                // Method with 2 int parameters & int-array return-type
  int s=               //  Step integer, starting at:
        a<b?1          //   1 if the first input is smaller than the second
        :-1;           //   -1 otherwise
      i=               //  Array-index integer, starting at:
        a!=b?          //   If the inputs aren't equal:
         (b-a)*s+1     //    Set it to the absolute difference + 1
        :              //   Else:
         2,            //    Set it to 2
      r[]=new int[i];  //  Result-array of that size
  for(r[0]=a,          //  Fill the first value with the first input
      r[1]=b;          //  And the second value with the second input
      i>2;)            //  Loop `i` downwards in the range [`i`,2):
    r[--i]=            //   Decrease `i` by 1 first with `--i`
                       //   Set the `i`'th array-value to:
           b-=s;       //    If the step integer is 1: decrease `b` by 1
                       //    If the step integer is -1: increase `b` by 1
                       //    And set the array-value to this modified `b`
  return r;}           //  Return the result-array

¿No hay algo en la biblioteca estándar de Java para hacer rangos de enteros? ¿O es demasiado detallado para usar?
— Precioso

@ Οurous De hecho, es demasiado detallado: a->b->{var L=java.util.stream.IntStream.range(a,b).boxed().collect(java.util.Collectors.toList());L.add(0,b);L.add(0,a);return L;}(130 bytes)
— Kevin Cruijssen

¿Es Java 8 o Java 10? Debido a "var" ^^ '
— Neyt

1
@Neyt Ah, arreglado. Mi versión inicial con la matriz a continuación no se usó var, por lo que generalmente pongo esos en 8, y los que sí usan varcomo 10 (y los que usan String.repeatcomo 11). :) Olvidé actualizarlo después de agregar las respuestas de Lista y Cadena, debería corregirse ahora. Gracias.
— Kevin Cruijssen

5

APL (Dyalog Extended) , 5 bytes

Función de infijo anónimo.

,,…~,

Pruébalo en línea!

, el primero y el último (literalmente, la concatenación de los argumentos)

, y (lit. concatenado a)

… el rango

~ sin

, el primero y el último (literalmente, la concatenación de los argumentos)


Bien, ¿así que supongo que vas a usar esto para todo tu golf a partir de ahora?
— Zacharý

@ Zacharý Probablemente solo si el código es significativamente más corto o más simple.
— Adám


4

Jalea , 4 bytes

,œ|r

Pruébalo en línea!

Cómo funciona

,œ|r  Main link. Left argument: a. Right argument: b

,     Pair; yield [a, b].
   r  Range; yield [a, ..., b].
 œ|   Perform multiset union.

4

J 26 bytes

,,[|.@]^:(>{.)<.+1}.i.@|@-

Pruébalo en línea!

Explicación:

Un verbo diádico (toma argumento izquierdo y derecho)

                         -    subtracts the arguments
                       |@     and finds the absolute value
                    i.@       and makes a list 0..absolute difference
                 1}.          drops the fist element
                +             adds to the entire list
              <.              the smaller of the arguments
   |.@]                       reverses the list
       ^:                     only if
  [                           the left argument
         (>{.)                is greater than the first item of the list
 ,                            appends the list to
,                             the right argument appended to the left one

1
,,[:}.@}:<.+i.@-@(+*)@-para 23 bytes y sin carcasa especial en el orden relativo de argumentos (más bien: está oculto dentro del signum *). Siento que esto podría bajar a menos de 20 pero estoy cansado.
— Jonás

@ Jonás ¡Gracias! La solución de Btw FrownyFrog es mucho mejor que la mía, por lo que no voy a seguir jugando al golf.
— Galen Ivanov


4

J , 13 bytes

,,<.+i.@-~-.=

Pruébalo en línea!

     i.@-~       range [0 .. |difference|-1], reverse if the difference is positive
          -.=    remove the zero (either "=" is 0 or there’s nothing to remove)
  <.+            to each element add the smaller of the args
,,               prepend args

Buena solución! Me olvidé por completo i.con un argumento negativo.
— Galen Ivanov

1
¡esto es hermoso!
— Jonás

3

Lote, 107 bytes

@echo %1
@echo %2
@for %%s in (1 -1)do @for /l %%i in (%1,%%s,%2)do @if %1 neq %%i if %%i neq %2 echo %%i

Toma datos como argumentos de línea de comandos. Explicación:

@echo %1
@echo %2

Salida de los dos enteros.

@for %%s in (1 -1)do

Pruebe los rangos ascendentes y descendentes.

@for /l %%i in (%1,%%s,%2)do

Recorrer el rango inclusivo.

@if %1 neq %%i if %%i neq %2

Excluir los dos enteros.

echo %%i

Salida del valor actual.


3

Pyth , 5 bytes

+QtrF

Entrada es una lista de dos elementos, [input 1, input 2]. Pruébelo en línea aquí , o verifique todos los casos de prueba a la vez aquí .

+QtrFQ   Implicit: Q=eval(input())
         Trailing Q inferred
   rFQ   Generate range [input 1 - input 2)
  t      Discard first element
+Q       Prepend Q

Usar en Flugar de .*en listas de 2 elementos es un truco brillante que absolutamente usaré de ahora en adelante.
— hakr14




3

Python 2 , 52 47 41 bytes

lambda i,j:[i,j]+range(i,j,(i<j)*2-1)[1:]

Pruébalo en línea!

-5 gracias a @JoKing

-6 cortando el primer elemento del rango (idea robada y con crédito a @TFeld)

Versión no lambda ...

Python 2 , 51 49 47 bytes

i,j=input();print[i,j]+range(i,j,(i<j)*2-1)[1:]

Pruébalo en línea!

-2 con agradecimiento a @JoKing



3

PHP (102 bytes)

function t($a,$b){count($r=range($a,$b))>1?array_splice($r,1,0,array_pop($r)):$r=[$a,$b];print_r($r);}

Salvadera

Desafortunadamente (para el golf) PHP tiene nombres de funciones bastante detallados, que contribuyen mucho a la longitud. Pero la idea básica es crear un rango, luego quitar el último elemento y volver a unirlo en el desplazamiento 1. Por 4,4ejemplo, tuve que agregar count($r=range($a,$b))>1?...:$r=[$a,$b];que agrega bastante, y desafortunadamente array_splice()es por referencia que me golpeó por unos cuantos más bytes ( $r= and a ;). Todo por ese "caso de borde", jajaja.

Bueno, de todos modos disfruta!


No creo que este sea un enfoque correcto para el golf de código. Mira este function t($a,$b){$o=array($a,$b);for($i=$a+1;$i<$b;$i++)$o[]=$i;print_r($o);}
— th3pirat3

O algo asífunction t($a,$b){echo $a.$b;for($i=$a+1;$i<$b;$i++)echo $i};
— th3pirat3

1
Tiene que ser una función y debe generar una matriz. Si tienes una mejor respuesta, entonces puedes publicarla.
— ArtisticPhoenix

Lo edité, ¿es una presentación válida ahora? ¿Lo pongo como una nueva respuesta o qué?
— th3pirat3

Eso depende completamente de ti, solo quería hacerlo sin un lazo ... jajaja
— ArtisticPhoenix

3

Clojure , 61 bytes

(fn[[a b]](def s(if(> a b)-1 1))(list* a b(range(+ a s)b s)))

Una función anónima que toma un 2-vector como entrada y devuelve una lista.

Pruébalo en línea!

Explicación

(fn [[a b]] ; An anonymous function that accepts a 2-vector as input, and destructures it to a and b
  (def s (if (> a b) -1 1)) ; If a > b assigns -1 to s and assigns 1 to s otherwise. This determines the order of the elements of the output list.
  (list* a b ; Creates a list with a and b as the first two elements. The remaining elements will be appended from the following range:
    (range (+ a s) b s))) ; A range starting at a+s and ending at b with step s

3

D , 85 bytes

T[]f(T)(T a,T b){T[]v=[a,b];T c=2*(b>a)-1;for(T i=a+c;a!=b&&b!=i;i+=c)v~=i;return v;}

Pruébalo en línea!

Un puerto de la respuesta C ++ de @ HatsuPointerKun en D.


3

TI-BASIC, 35 34 bytes

-1 byte de Misha Lavrov

Prompt A,B
Disp A,B
cos(π(A>B
For(I,A+Ans,B-Ans,Ans
Disp I
End

2
Y un byte más al reemplazar 1-2(A>Bcon cos(π(A>B.
— Misha Lavrov

@MishaLavrov seq(no funcionaría para entradas donde Ay Bson iguales, desafortunadamente :(
— kamoroso94

Es cierto, además, omití un argumento de seq(, por lo que ya no estoy convencido de que incluso sea más pequeño. Aún así, el cos(truco debería ayudar.
— Misha Lavrov

2

Carbón de leña , 15 bytes

IE²NI…⊕θηI⮌…⊕ηθ

Pruébalo en línea! El enlace es a la versión detallada del código. Explicación:

IE²N

Imprima las entradas en líneas separadas.

I…⊕θη

Imprima el rango ascendente, si lo hay.

I⮌…⊕ηθ

Imprima el rango inverso ascendente inverso, si lo hay.


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.