37
\$\begingroup\$

Given two integers, output the two integers, and then the range between them (excluding both).

The order of the range must be the same as the input.

Examples:

 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]
\$\endgroup\$
12
  • \$\begingroup\$ I guess we can't take the inputs in pre-ordered order? \$\endgroup\$ Commented Nov 8, 2018 at 9:55
  • 1
    \$\begingroup\$ Is this output format acceptable? Note the newline \$\endgroup\$
    – Luis Mendo
    Commented Nov 8, 2018 at 10:48
  • 1
    \$\begingroup\$ @LuisMendo I'll allow it :) \$\endgroup\$
    – TFeld
    Commented Nov 8, 2018 at 10:55
  • 1
    \$\begingroup\$ I assume a space or newline delimited string is also allowed as output, instead of an actual array/list/stream? \$\endgroup\$ Commented Nov 8, 2018 at 13:06
  • 3
    \$\begingroup\$ @KevinCruijssen Any reasonable I/O is acceptable. \$\endgroup\$
    – TFeld
    Commented Nov 8, 2018 at 13:08

63 Answers 63

16
\$\begingroup\$

R, 39 33 30 bytes

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

Try it online!

Thanks for saved bytes to user2390246 and J.Doe.

\$\endgroup\$
3
  • \$\begingroup\$ You could save a few bytes by taking the input as a vector rather than as two separate integers. \$\endgroup\$ Commented Nov 8, 2018 at 11:47
  • \$\begingroup\$ Yeah, that's reasonable, and it actually then becomes even shorter as a full program rather than function. \$\endgroup\$
    – Kirill L.
    Commented Nov 8, 2018 at 12:04
  • \$\begingroup\$ You can abuse the fact the : operator uses the first element of both args for 30 bytes \$\endgroup\$
    – J.Doe
    Commented Nov 8, 2018 at 12:20
13
\$\begingroup\$

05AB1E, 4 bytes

Ÿ¦¨«

Try it online!

Explanation

    Ÿ      # inclusive range [a ... b]
     ¦¨    # remove the first and last element
       «   # append to input
\$\endgroup\$
12
\$\begingroup\$

Python 3, 52 48 47 42 41 bytes

lambda a,b:[a,b,*range(a,b,-(a>b)|1)[1:]]

Try it online!


Combined former implementations.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can remove the space at or-1 to save a byte. \$\endgroup\$ Commented Nov 8, 2018 at 9:56
10
\$\begingroup\$

Python 2 (Cython), 36 35 bytes

lambda x:x+range(*x,-cmp(*x)|1)[1:]

Thanks to @nwellnhof for golfing off 1 byte!

Try it online!


Python 2, 37 bytes

lambda x:x+range(*x+[-cmp(*x)|1])[1:]

Thanks to @JonasAusevicius for the port to CPython!

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ This can be applied to standard Python 2 at 37 bytes, making it the shortest answer yet: lambda x:x+range(*x+[-cmp(*x)|1])[1:]. Nice solution \$\endgroup\$
    – Hori
    Commented Nov 8, 2018 at 14:17
8
\$\begingroup\$

Perl 6, 26 22 bytes

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

Try it online!

Explanation

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

Python 2, 40 bytes

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Really like -(y<x)|1. very cool but I can't work out why it works! Any chance you can explain it? \$\endgroup\$
    – ElPedro
    Commented Nov 8, 2018 at 19:06
  • 2
    \$\begingroup\$ @ElPedro Basically, y<x checks if y is strictly less than x, and returns True if it is, False otherwise. After that, unary - is applied to it, which converts True to -1 and False to 0. The last step is to bitwise OR this number with 1. This obviously leaves 1 (0b1) unaffected, and also leaves -1 (-0b1) unaffected (the sign bit of -1 is set, so it's kept as such). However, it does convert 0 to 1, so that range doesn't complain about me using a step of 0. \$\endgroup\$ Commented Nov 8, 2018 at 19:32
  • \$\begingroup\$ That is seriously cool and very clever. If I could upvote twice I would. Many thanks for the explanation. \$\endgroup\$
    – ElPedro
    Commented Nov 8, 2018 at 20:27
6
\$\begingroup\$

Python 3, 64 62 51 bytes

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

Try it online!

Python 2, 58 45 bytes

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

Try it online!

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Because an empty list is falsey, you can remove the a<=b and from both answers \$\endgroup\$
    – TFeld
    Commented Nov 8, 2018 at 10:03
  • \$\begingroup\$ You could also use + instead of or \$\endgroup\$
    – TFeld
    Commented Nov 8, 2018 at 10:13
  • 1
    \$\begingroup\$ Python 3 down to 47 bytes: lambda a,b:[a,b,*range(a+1,b),*range(a-1,b,-1)] \$\endgroup\$
    – mypetlion
    Commented Nov 14, 2018 at 20:48
6
\$\begingroup\$

Python 2, 47 41 40 bytes

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

Try it online!

Here's mine, now that a lot of other Python answers have been posted

-6 bytes, thanks to G B

\$\endgroup\$
3
  • \$\begingroup\$ Taking advantage of the empty range when it's invalid is a smart way to deal with forward or backwards lists. I could see that being very useful and is a nice trick to know exists. \$\endgroup\$
    – akozi
    Commented Nov 8, 2018 at 12:21
  • 2
    \$\begingroup\$ 41 bytes using a single range: range(a,b,(a<b)*2-1) \$\endgroup\$
    – G B
    Commented Nov 8, 2018 at 12:35
  • \$\begingroup\$ a<b or-1 is shorter for the 3rd range parameter. The shortest I got was lambda x,y:[x,y]+range(x+(x<y or-1),y,x<y or-1) \$\endgroup\$
    – mbomb007
    Commented Nov 24, 2018 at 4:42
6
\$\begingroup\$

Japt, 8 bytes

cUr!õ kU

Try it here

             :Implicit input of array U
c            :Concatenate
 Ur          :  Reduce U by
   !õ        :   Inclusive range
      kU     :  Remove all elements in original U
\$\endgroup\$
1
  • \$\begingroup\$ The 5-byte version seems to now fail for the 4,4 test case... \$\endgroup\$ Commented Jan 24, 2021 at 14:12
5
\$\begingroup\$

Jelly, 4 bytes

,œ|r

Try it online!

How it works

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

,     Pair; yield [a, b].
   r  Range; yield [a, ..., b].
 œ|   Perform multiset union.
\$\endgroup\$
5
\$\begingroup\$

JavaScript (ES6), 51 bytes

Takes input as (a)(b).

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

Try it online!

Commented

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
\$\endgroup\$
5
\$\begingroup\$

Java 10, 109 108 104 102 93 62 bytes

Using a space-delimited String:

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

Try it online.

Using a List:

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

Try it online.

(a<b?++a<b:--a>b can be ++a<b||(a-=2)>b for the same byte-count: Try it online for the String or Try it online for the List.)


Old (109 108 104 102 101 bytes) answer using an array:

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 thanks to @nwellnhof.

Try it online.

Explanation:

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
\$\endgroup\$
4
  • \$\begingroup\$ Isn't there anything in Java's standard library for making ranges of integers? Or it is just too verbose to use? \$\endgroup\$
    – Οurous
    Commented Nov 8, 2018 at 11:17
  • \$\begingroup\$ @Οurous It's indeed too verbose: 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) \$\endgroup\$ Commented Nov 8, 2018 at 12:11
  • \$\begingroup\$ Is it Java 8 or Java 10 ? Because of "var" ^^' \$\endgroup\$
    – Neyt
    Commented Nov 9, 2018 at 10:45
  • 1
    \$\begingroup\$ @Neyt Ah, fixed. My initial version with the array below didn't use var, which is why I usually put those at 8, and the ones that does use var as 10 (and the ones using String.repeat as 11). :) Forgot to update it after adding the List and String answers, should be corrected now. Thanks. \$\endgroup\$ Commented Nov 9, 2018 at 10:51
5
\$\begingroup\$

APL (Dyalog Extended), 5 bytes

Anonymous infix function.

,,…~,

Try it online!

, the first and last (lit. the concatenation of the arguments)

, and (lit. concatenated to)

 the range

~ without

, the first and last (lit. the concatenation of the arguments)

\$\endgroup\$
2
  • \$\begingroup\$ Nice, so I assume you're going to be using this for all of your golfing from now on? \$\endgroup\$
    – Adalynn
    Commented Nov 14, 2018 at 12:50
  • \$\begingroup\$ @Zacharý Probably only if the code is significantly shorter or simpler. \$\endgroup\$
    – Adám
    Commented Nov 14, 2018 at 12:56
4
\$\begingroup\$

Haskell, 34 bytes

a#b=a:b:[a+1..b-1]++[a-1,a-2..b+1]

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ This does not work. GHC interprets b-1 as b $ (-1). Use b- 1 instead. \$\endgroup\$ Commented Nov 10, 2018 at 20:34
  • \$\begingroup\$ @MarkNeu: it does work. See TIO link. \$\endgroup\$
    – nimi
    Commented Nov 10, 2018 at 21:12
  • \$\begingroup\$ Oh, sorry! I had NegativeLiterals on. \$\endgroup\$ Commented Nov 10, 2018 at 21:15
4
\$\begingroup\$

J, 26 bytes

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

Try it online!

Explanation:

A dyadic verb (takes left and right argument)

                         -    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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ ,,[:}.@}:<.+i.@-@(+*)@- for 23 bytes and no special casing on relative argument ordering (rather: it's hidden inside the signum *). i feel like this could get down under 20 but i'm tired. \$\endgroup\$
    – Jonah
    Commented Nov 10, 2018 at 6:53
  • \$\begingroup\$ @Jonah Thank you! Btw FrownyFrog's solution is way better than mine, so I 'm not going to golf it any further. \$\endgroup\$ Commented Nov 10, 2018 at 7:30
4
\$\begingroup\$

Octave, 45 bytes

@(a,b)[a b linspace(a,b,(t=abs(a-b))+1)(2:t)]

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ IF the first is larger than the second, the range must be descending \$\endgroup\$
    – TFeld
    Commented Nov 8, 2018 at 11:03
  • \$\begingroup\$ Oh man, I can't read \$\endgroup\$
    – Luis Mendo
    Commented Nov 8, 2018 at 11:03
  • \$\begingroup\$ I ended up changing the language \$\endgroup\$
    – Luis Mendo
    Commented Nov 8, 2018 at 14:33
4
\$\begingroup\$

J, 13 bytes

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

Try it online!

     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
\$\endgroup\$
2
  • \$\begingroup\$ Nice solution! I totally forgot abouti. with negative argument. \$\endgroup\$ Commented Nov 8, 2018 at 17:40
  • 1
    \$\begingroup\$ this is gorgeous! \$\endgroup\$
    – Jonah
    Commented Nov 10, 2018 at 14:55
3
\$\begingroup\$

Batch, 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

Takes input as command-line arguments. Explanation:

@echo %1
@echo %2

Output the two integers.

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

Try both ascending and descending ranges.

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

Loop over the inclusive range.

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

Exclude the two integers.

echo %%i

Output the current value.

\$\endgroup\$
3
\$\begingroup\$

Pyth, 5 bytes

+QtrF

Input is a two-element list, [input 1, input 2]. Try it online here, or verify all the test cases at once here.

+QtrFQ   Implicit: Q=eval(input())
         Trailing Q inferred
   rFQ   Generate range [input 1 - input 2)
  t      Discard first element
+Q       Prepend Q
\$\endgroup\$
1
  • \$\begingroup\$ Using F instead of .* on 2-element lists is a brilliant trick that I will absolutely be using from here on. \$\endgroup\$
    – hakr14
    Commented Nov 8, 2018 at 16:31
3
\$\begingroup\$

Red, 75 bytes

func[a b][s: sign? d: b - a prin[a b]loop absolute d - s[prin[""a: a + s]]]

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Clean, 49 bytes

import StdEnv
@a b=init[a,b:tl[a,a+sign(b-a)..b]]

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Ruby, 33 40 bytes

->a,b{[a,b]+[*a..b,*a.downto(b)][1..-2]}

Try it online!

Temporary fix, trying to find a better idea

\$\endgroup\$
2
  • 3
    \$\begingroup\$ For [4,4] this gives only one [4] \$\endgroup\$
    – Kirill L.
    Commented Nov 8, 2018 at 9:36
  • \$\begingroup\$ You are right, I fixed it. \$\endgroup\$
    – G B
    Commented Nov 23, 2018 at 9:32
3
\$\begingroup\$

Python 2, 52 47 41 bytes

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

Try it online!

-5 with thanks to @JoKing

-6 by slicing the first element from the range (idea stolen from and with credit to @TFeld)

Non-lambda version...

Python 2, 51 49 47 bytes

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

Try it online!

-2 with thanks to @JoKing

\$\endgroup\$
0
3
\$\begingroup\$

APL (Dyalog Classic), 29 bytes

{⍺,⍵,(⌽⍣(⍺>⍵))(⍺⌊⍵)+¯1↓⍳|⍺-⍵}

Try it online!

A port of my J solution

\$\endgroup\$
2
  • \$\begingroup\$ Wow, I'm surprised this is so long for a seemingly simple task. \$\endgroup\$
    – Quintec
    Commented Nov 9, 2018 at 0:43
  • \$\begingroup\$ @Quintec Probably it can be golfed, or maybe another algorithm will result in much shorter solution. \$\endgroup\$ Commented Nov 9, 2018 at 4:35
3
\$\begingroup\$

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

Sandbox

Unfortunately (for golf) PHP has rather verbose function names, which contribute a lot to the length. But the basic idea is to create a range, then pop off the last element and stitch it back in at offset 1. For the 4,4 example I had to add count($r=range($a,$b))>1?...:$r=[$a,$b]; which adds quite a bit, and unfortunately array_splice() is by reference which hit me for a few more bytes ($r= and a ;). All because of that "edge case", lol.

Well anyway enjoy!

\$\endgroup\$
7
  • \$\begingroup\$ I dont think that this is a right approach for code golf. Check this one function t($a,$b){$o=array($a,$b);for($i=$a+1;$i<$b;$i++)$o[]=$i;print_r($o);} \$\endgroup\$
    – th3pirat3
    Commented Nov 10, 2018 at 21:47
  • \$\begingroup\$ Or something like this function t($a,$b){echo $a.$b;for($i=$a+1;$i<$b;$i++)echo $i}; \$\endgroup\$
    – th3pirat3
    Commented Nov 10, 2018 at 21:48
  • 1
    \$\begingroup\$ It has to be a function and it has to output an array. If you have a better answer your more then welcome to post it. \$\endgroup\$ Commented Nov 10, 2018 at 21:50
  • \$\begingroup\$ I edited it, is that a valid submission now? Shall I put it as a new answer or what? \$\endgroup\$
    – th3pirat3
    Commented Nov 10, 2018 at 21:52
  • \$\begingroup\$ That is entirely up to you, I just wanted to do it without a loop ... lol \$\endgroup\$ Commented Nov 10, 2018 at 21:53
3
\$\begingroup\$

Clojure, 61 bytes

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

An anonymous function that takes a 2-vector as input and returns a list.

Try it online!

Explanation

(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
\$\endgroup\$
3
\$\begingroup\$

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

Try it online!

A port of @HatsuPointerKun's C++ answer into D.

\$\endgroup\$
3
\$\begingroup\$

TI-BASIC, 35 34 bytes

-1 byte from Misha Lavrov

Prompt A,B
Disp A,B
cos(π(A>B
For(I,A+Ans,B-Ans,Ans
Disp I
End
\$\endgroup\$
3
  • 2
    \$\begingroup\$ And one more byte by replacing 1-2(A>B with cos(π(A>B. \$\endgroup\$ Commented Nov 8, 2018 at 20:55
  • \$\begingroup\$ @MishaLavrov seq( wouldn't work for inputs where A and B are the same, unfortunately :( \$\endgroup\$
    – kamoroso94
    Commented Nov 8, 2018 at 22:33
  • \$\begingroup\$ True - also, I left out an argument of seq(, so I'm no longer convinced it even is smaller. Still, the cos( trick should help. \$\endgroup\$ Commented Nov 8, 2018 at 22:34
3
\$\begingroup\$

JavaScript, 73 bytes

Without recursion:

(s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))]

Try it:

f=(s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))]

console.log(JSON.stringify(f(0,5)));
console.log(JSON.stringify(f(-3,8)));
console.log(JSON.stringify(f(4,4)));
console.log(JSON.stringify(f(4,5)));
console.log(JSON.stringify(f(8,2)));
console.log(JSON.stringify(f(-2,-7)));

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 15 bytes

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

Try it online! Link is to verbose version of code. Explanation:

IE²N

Print the inputs on separate lines.

I…⊕θη

Print the ascending range, if any.

I⮌…⊕ηθ

Print the reverse ascending reverse range, if any.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.