25
\$\begingroup\$

Here's the challenge. Write some code to output all the integers in a range. Sounds easy, but here's the tricky part. It will start with the lowest number, then the highest. Then the lowest number which isn't yet in the array. Then the highest which isn't yet in it.

Example:

Lets take 1 to 5 as our start

The numbers are [1, 2, 3, 4, 5].

We take the first, so [1]. Remaining numbers are [2, 3, 4, 5]. We take the last, new array is [1, 5]. Remaining numbers are [2, 3, 4]. We take the first, new array is [1, 5, 2]. Remaining numbers are [3, 4]. We take the last, new array is [1, 5, 2, 4]. Remaining numbers are [3]. We take the first, new array is [1, 5, 2, 4, 3]. No numbers remaining, we're done. Output [1, 5, 2, 4, 3]

Rules:

  • This is code golf, write it in the fewest bytes, any language.
  • No standard loopholes.
  • Links to an online interpreter, please? (E.g. https://tio.run/)
  • Two inputs, both integers. Low end of range, and high end of range.
  • I don't mind what the data type of the output is, but it must show the numbers in the correct order.

Examples

Low: 4 High: 6 Result: 4 6 5


Low: 1 High: 5 Result: 1 5 2 4 3


Low: -1 High: 1 Result: -1 1 0


Low: -1 high: 2 Result: -1 2 0 1


Low: -50 High: 50 Result: -50 50 -49 49 -48 48 -47 47 -46 46 -45 45 -44 44 -43 43 -42 42 -41 41 -40 40 -39 39 -38 38 -37 37 -36 36 -35 35 -34 34 -33 33 -32 32 -31 31 -30 30 -29 29 -28 28 -27 27 -26 26 -25 25 -24 24 -23 23 -22 22 -21 21 -20 20 -19 19 -18 18 -17 17 -16 16 -15 15 -14 14 -13 13 -12 12 -11 11 -10 10 -9 9 -8 8 -7 7 -6 6 -5 5 -4 4 -3 3 -2 2 -1 1 0


Happy golfing!

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Almost duplicate (the difference being that this one requires reversing the second half before merging). \$\endgroup\$ Feb 13, 2019 at 15:13
  • \$\begingroup\$ is the input always going to be in the order of low end, high end? \$\endgroup\$
    – Sumner18
    Feb 13, 2019 at 16:14
  • 1
    \$\begingroup\$ @Sumner18 yes. The community here is dead-set against input validation, and I haven’t asked for a reverse-order input, so we can assume it’ll always be low - high. \$\endgroup\$
    – AJFaraday
    Feb 13, 2019 at 16:21
  • 1
    \$\begingroup\$ @Sumner18 How these challenges usually work is that we don't care how invalid inputs are handled. Your code is only judged to be successful by how it deals with valid inputs (i.e. both are integers, the first is lower than the second) \$\endgroup\$
    – AJFaraday
    Feb 13, 2019 at 16:36
  • 1
    \$\begingroup\$ @AJFaraday: you should add a note to the main post indicating that X will be always strictly lower than Y (i.e. X != Y), I missed this comment ;) \$\endgroup\$
    – digEmAll
    Feb 13, 2019 at 18:23

57 Answers 57

15
\$\begingroup\$

R, 38 37 36 bytes

function(a,b)rbind(a:b,b:a)[a:b-a+1]

Try it online!

  • -1 byte thanks to @user2390246
  • -1 byte thanks to @Kirill L.

Exploiting the fact that R stores matrices column-wise

\$\endgroup\$
4
  • \$\begingroup\$ Using rbind is much better than my approach, but you can save 1 byte by using [seq(a:b)] instead of unique. \$\endgroup\$ Feb 13, 2019 at 18:03
  • \$\begingroup\$ You're right, I missed the comment where has been specified that a < b (never equal), so we can use seq(a:b) \$\endgroup\$
    – digEmAll
    Feb 13, 2019 at 18:06
  • \$\begingroup\$ @digEmAll My solution was essentially a literal interpretation of the puzzle, I never would have even thought of doing something such as this. Impressive, have an upvote! \$\endgroup\$
    – Sumner18
    Feb 13, 2019 at 18:07
  • 1
    \$\begingroup\$ -1 more \$\endgroup\$
    – Kirill L.
    Feb 13, 2019 at 20:32
11
\$\begingroup\$

Haskell, 30 bytes

a%b=a:take(b-a)(b:(a+1)%(b-1))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Dammit! I have just found the exact same solution. Oh well \$\endgroup\$ Feb 14, 2019 at 13:49
8
\$\begingroup\$

R, 65 64 61 60 bytes

-1 byte thanks to Robert S.

-4 more thanks to digEmAll

x=scan();z=x:x[2];while(sum(z|1)){cat(z[1],"");z=rev(z[-1])}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ You can replace length(z) with sum(z|1) to save 1 byte :) \$\endgroup\$
    – Robert S.
    Feb 13, 2019 at 17:09
  • \$\begingroup\$ I don't understand how that works but I guess it does. sum(z|1) seems like it would always evaluate to at least 1, which would cause the while loop to loop endlessly. but apparently not \$\endgroup\$
    – Sumner18
    Feb 13, 2019 at 17:27
  • 4
    \$\begingroup\$ z is a vector. each element of that vector is |ed with 1. Which is always equal to 1. When you take the sum, you have a vector filled with TRUEs so the result is equal to the length of the vector. If the vector is empty, you the is nothing to | with so the output vector is logical(0). When you take that sum, it's 0 \$\endgroup\$
    – OganM
    Feb 13, 2019 at 23:59
7
\$\begingroup\$

Haskell, 39 bytes

a#b|a>b=a:b#(a-1)|a<b=a:b#(a+1)|1>0=[a]

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Python 2, 44 bytes

f=lambda a,b:[a]*(a==b)or[a]+f(b,a-cmp(a,b))

Try it online!

\$\endgroup\$
5
\$\begingroup\$

PowerShell, 59 48 bytes

param($a,$b)(($z=0..($b-$a))|%{$a+$_;$b-$_})[$z]

Try it online!

(Seems long...)

Takes input $a and $b, constructs the range 0 .. ($b-$a), stores that into $z, then loops through that range. The looping through that range is just used as a counter to ensure we get enough iterations. Each iteration, we put $a and $b on the pipeline with addition/subtraction. That gives us something like 1,5,2,4,3,3,4,2,5,1 so we need to slice into that from 0 up to the $b-$a (i.e., the count) of the original array so we're only left with the appropriate elements. That's left on the pipeline and output is implicit.

-11 bytes thanks to mazzy.

\$\endgroup\$
2
  • \$\begingroup\$ 48 bytes \$\endgroup\$
    – mazzy
    Feb 13, 2019 at 17:29
  • \$\begingroup\$ @mazzy Ah, I like that $b-$a trick -- that's clever! \$\endgroup\$ Feb 13, 2019 at 17:40
5
\$\begingroup\$

05AB1E, 6 bytes

ŸDvć,R

Try it online!

Explanation

Ÿ        # push range [min ... max]
 D       # duplicate
  v      # for each element in the copy
   ć,    # extract and print the head of the original list
     R   # and then reverse it
\$\endgroup\$
9
  • \$\begingroup\$ Ÿ2ä`R.ι non iterative using interleave, but this is still much better. \$\endgroup\$ Feb 14, 2019 at 2:36
  • 1
    \$\begingroup\$ @MagicOctopusUrn: I tried a non-iterative solution first, but it was even worse since I didn't know about ;) \$\endgroup\$
    – Emigna
    Feb 14, 2019 at 7:36
  • \$\begingroup\$ Similar as what I had in mind, so obvious +1 from me. I do like your alternative 7-byter as well through, @MagicOctopusUrn. :) \$\endgroup\$ Feb 14, 2019 at 8:28
  • 1
    \$\begingroup\$ @KristianWilliams: Seems to be working for me. \$\endgroup\$
    – Emigna
    Feb 14, 2019 at 9:08
  • 1
    \$\begingroup\$ @KevinCruijssen: I switched to a pair instead as that felt more intuitive anyways :) \$\endgroup\$
    – Emigna
    Feb 14, 2019 at 10:50
4
\$\begingroup\$

Japt, 14 bytes

òV
íUs w)c vUl

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ 13 bytes, using the same approach. \$\endgroup\$
    – Shaggy
    Feb 13, 2019 at 23:01
4
\$\begingroup\$

Stax, 7 bytes

É╓ÅìΔà▲

Run and debug it

\$\endgroup\$
4
\$\begingroup\$

R, 51 bytes

function(x,y,z=x:y)matrix(c(z,rev(z)),2,,T)[seq(z)]

Try it online!

Explanation: For a sequence x:y of length N, create a two-by-N matrix consisting of the sequence x:y in the top row and y:x in the bottom row matrix(c(z,rev(z)),2,,T). If we select the first N elements of the matrix [seq(z)], they will be chosen by column, giving the required output.

Outgolfed by digEmAll

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I just posted a very similar approach 30 seconds before you :D \$\endgroup\$
    – digEmAll
    Feb 13, 2019 at 18:01
  • \$\begingroup\$ @digEmAll Yes, but yours is a lot better! \$\endgroup\$ Feb 13, 2019 at 18:03
4
\$\begingroup\$

cQuents, 19 bytes

#|B-A+1&A+k-1,B-k+1

Try it online!

Note that it does not work on TIO right now because TIO's interpreter is not up to date.

Explanation

#|B-A+1&A+k-1,B-k+1
                      A is the first input, B is the second input
#|B-A+1               n = B - A + 1
       &              Print the first n terms of the sequence
                      k starts at 1 and increments whenever we return to the first term
        A+k-1,         Terms alternate between A + k - 1 and
              B-k+1     B - k + 1
                       increment k
\$\endgroup\$
4
\$\begingroup\$

Haskell, 39 bytes

f(a:b)=a:f(reverse b)
f x=x
a#b=f[a..b]

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Haskell, 30 bytes

l%h=l:take(h-l)(h:(l+1)%(h-1))

Usage: 3%7 gives `[3,7,4,6,5]

For the inputs l, h the function calls recursively with the inputs l+1, h-1, and adds l,h to the beggining. Instead of any halting condition, the code uses take(h-l) to shorten the sequence to the right length (which would otherwise be an infinite sequence of increasing and decreasing numbers).

\$\endgroup\$
4
\$\begingroup\$

C# (Visual C# Interactive Compiler), 46 bytes

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

Saved 4 bytes thanks to dana!

Try it online!

C# (Visual C# Interactive Compiler), 65 bytes

void z(int a,int b){if(a<=b){Write(a+(b>a?b+"":""));z(a+1,b-1);}}

Try it online!

\$\endgroup\$
0
4
\$\begingroup\$

JVM bytecode (OpenJDK asmtools JASM), 449 bytes

enum b{const #1=Method java/io/PrintStream.print:(I)V;static Method a:(II)V stack 2 locals 4{getstatic java/lang/System.out:"Ljava/io/PrintStream;";astore 3;ldc 0;istore 2;l:iload 2;ldc 1;if_icmpeq t;aload 3;iload 0;invokevirtual #1;iinc 0,1;iinc 2,1;goto c;t:aload 3;iload 1;invokevirtual #1;iinc 1,-1;iinc 2,-1;c:aload 3;ldc 32;i2c;invokevirtual java/io/PrintStream.print:(C)V;iload 0;iload 1;if_icmpne l;aload 3;iload 0;invokevirtual #1;return;}}

Ungolfed (and slightly cleaner)

 enum b {    
    public static Method "a":(II)V stack 5 locals 4 {
        getstatic "java/lang/System"."out":"Ljava/io/PrintStream;";
        astore 3;
        ldc 0;
        istore 2;
    loop:
        iload 2;
        ldc 1;
        if_icmpeq true;
    false:
        aload 3;
        iload 0;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        iinc 0,1;
        iinc 2,1;
        goto cond;
    true:
        aload 3;
        iload 1;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        iinc 1,-1;
        iinc 2,-1;
        goto cond;
    cond:
        iload 0;
        iload 1;
        if_icmpne loop;
        aload 3;
        iload 0;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        return;
    }
}

Standalone function, needs to be called from Java as b.a(num1,num2).

Explanation

This code uses the method parameters as variables, as well as a boolean in local #3 deciding which number to output. Each loop iteration either the left or right is output, and that number is incremented for the left or decremented for the right. Loop continues until both numbers are equal, then that number is output.

...I have a distinct feeling I'm massively outgunned on the byte count

\$\endgroup\$
4
\$\begingroup\$

Wolfram Language (Mathematica), 56 54 bytes

This is my first time golfing!

f[a_,b_]:=(c=a~Range~b;Drop[c~Riffle~Reverse@c,a-b-1])

Try it online!

Saved 2 bytes using infix notation.

Explanation:

f[a_,b_]:=                                   \function of two variables
c=a~Range~b;                                 \list of integers from a to b 
                           Reverse@c         \same list in reverse
                  c~Riffle~Reverse@c         \interleave the two lists
             Drop[c~Riffle~Reverse@c,a-b-1]  \drop last |a-b-1| elements (note a-b-1 < 0)

Alternatively, we could use Take[...,b-a+1] for the same result.

Tests:

f[4, 6]
f[1, 5]
f[-1, 1]
f[-1, 2]

Ouput:

{4, 6, 5}
{1, 5, 2, 4, 3}
{-1, 1, 0}
{-1, 2, 0, 1}
\$\endgroup\$
4
  • \$\begingroup\$ The "Try it online" link returns a 403. "Sorry, you do not have permission to access this item." \$\endgroup\$ Feb 15, 2019 at 0:02
  • \$\begingroup\$ @RohitNamjoshi I updated the link \$\endgroup\$
    – Kai
    Feb 15, 2019 at 0:24
  • \$\begingroup\$ note that on TIO you can place header and footer code in the text boxes above and below the actual code box. This makes the code look cleaner, as well as allow you to take advantage the PPCG answer formatter (esc-s-g). Try it online! \$\endgroup\$
    – Jo King
    Feb 15, 2019 at 0:46
  • \$\begingroup\$ @JoKing much appreciated, I had never used it before! \$\endgroup\$
    – Kai
    Feb 15, 2019 at 0:50
4
\$\begingroup\$

MathGolf, 6 bytes

↨_x^─▀

Try it online!

Explanation with (1, 5)

↨        inclusive range from a to b    [1, 2, 3, 4, 5]
 _       duplicate TOS                  [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]
  x      reverse int/array/string       [1, 2, 3, 4, 5], [5, 4, 3, 2, 1]
   ^     zip top two elements on stack  [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]
    ─    flatten array                  [1, 5, 2, 4, 3, 3, 4, 2, 5, 1]
     ▀   unique elements of string/list [1, 5, 2, 4, 3]

The reason why this works is due to the fact that all elements in the output should be unique, so the unique elements operator will filter out the second half of the array, producing the correct output.

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

APL (dzaima/APL), 21 bytes

⌈⊢+.5×-+∘(⌽ׯ1*)∘⍳1+-

Try it online!

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

Japt, 7 bytes

Takes input as an array.

rõ
ÊÆÔv

Try it or run all test cases

         :Implicit input of array U=[low,high]
r        :Reduce by
 õ       :  Inclusive, reversed range (giving the range [high,low])
\n       :Reassign to U
Ê        :Length
 Æ       :Map the range [0,Ê)
  Ô      :  Reverse U
   v     :  Remove the first element
\$\endgroup\$
3
\$\begingroup\$

MATL, 8 bytes

&:t"1&)P

Try it online!

Explanation

&:      % Take two inputs (implicit). Two-input range
t       % Duplicate
"       % For each
  1&)   %   Push first element, then an array with the rest
  P     %   Reverse array
        % End (implicit). Display (implicit)
\$\endgroup\$
3
\$\begingroup\$

JavaScript, 40 bytes

l=>g=h=>h>l?[l++,h--,...g(h)]:h<l?[]:[l]

Try It Online!

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

Forth (gforth), 52 bytes

: f 2dup - 1+ 0 do dup . i 2 mod 2* 1- - swap loop ;

Try it online!

Explanation

Loop from 0 to (End - Start). Place End and Start on top of the stack.

Each Iteration:

  • Output the current number
  • Add (or subtract) 1 from the current number
  • Switch the current number with the other number

Code Explanation

: f           \ start new word definition
  2dup -      \ get the size of the range (total number of integers)
  1+ 0        \ add 1 to the size because forth loops are [Inclusive, Exclusive) 
  do          \ start counted loop from 0 to size+1
    dup .     \ output the current top of the stack
    i 2 mod   \ get the index of the loop modulus 2
    2* 1-     \ convert from 0,1 to -1,1
    -         \ subtract result from top of stack (adds 1 to lower bound and subtracts 1 from upper)
    swap      \ swap the top two stack numbers 
  loop        \ end the counted loop
;             \ end the word definition
\$\endgroup\$
3
\$\begingroup\$

Julia 0.7, 29 bytes

f(a,b)=[a:b b:-1:a]'[1:1+b-a]

Try it online!

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

Brachylog, 15 bytes

⟦₂{∅|b↔↰T&hg,T}

Input is a 2-element list [lo, hi]. Note that underscore is used for negative numbers. Try it online!

Explanation

⟦₂               2-argument inclusive range: [1,5] -> [1,2,3,4,5]
  {           }  Call this recursive predicate to calculate the output:
   ∅               Base case: the input is empty list; nothing to do
    |              Otherwise (recursive case):      [1,2,3,4,5]
     b             Behead the input list            [2,3,4,5]
      ↔            Reverse                          [5,4,3,2]
       ↰           Call the predicate recursively   [5,2,4,3]
        T          Label the result T
         &         Also, with the input list,
          h        Take the head                    1
           g       Wrap it in a list                [1]
            ,T     Append T from earlier            [1,5,2,4,3]
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 5 bytes

ŸÂ.ιÙ

Takes input as upper first.

Explanation:

ŸÂ.ιÙ   //full program
Ÿ       //push [min .. max]                stack: [[4, 5, 6]]
 Â      //push range and reversed range    stack: [[4, 5, 6], [6, 5, 4]]
  .ι    //interleave                       stack: [[4, 6, 5, 5, 6, 4]]
    Ù   //deduplicate                      stack: [[4, 6, 5]]

Try it online!

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

Perl 5 -ln, 37 bytes

@.=$_..<>;say shift@.,$/,pop@.while@.

Try it online!

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

Java (JDK), 52 bytes

(l,h,o)->{for(int i=0;l<=h;i^=1)o.add(i<1?l++:h--);}

Try it online!

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

Jelly, 6 bytes

rạṂ¥Þ,

Try it online!

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

Clean, 48 bytes

import StdEnv
$a b|a<>b=[a: $b(a+sign(b-a))]=[a]

Try it online!

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

Ruby, 37 36 33 bytes

f=->a,b{a>b ?[]:[a,b]|f[a+1,b-1]}

Try it online!

Recursive version with 3 bytes saved by G B.

Ruby, 38 bytes

->a,b{d=*c=a..b;c.map{d.reverse!.pop}}

Try it online!

Non-recursive version.

\$\endgroup\$
0

Your Answer

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

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