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\$
  • 2
    \$\begingroup\$ Almost duplicate (the difference being that this one requires reversing the second half before merging). \$\endgroup\$ – Peter Taylor Feb 13 at 15:13
  • \$\begingroup\$ is the input always going to be in the order of low end, high end? \$\endgroup\$ – Sumner18 Feb 13 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 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 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 at 18:23

56 Answers 56

2
\$\begingroup\$

JavaScript, 35 bytes

f=(a,b,s=1)=>a-b?a+[,f(b,a+s,-s)]:a

Try it online!

Thanks to Arnauld, 1 byte saved.

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

tinylisp, 48 bytes

(d f(q((A B)(c A(i(e A B)()(f B((i(l A B)a s)A 1

Try it online!

Explanation

The code defines a recursive function f that takes two arguments A and B, which are initially the lower and upper bounds of the range.

  • Base case: if A = B, return a list containing the single element A
  • Recursive case: prepend A to the result of a recursive call:
    • If A < B, recurse with arguments B and A+1
    • If A > B, recurse with arguments B and A-1

For example, with initial arguments 1 and 5:

Value   Next call
1       5, 2
5       2, 4
2       4, 3
4       3, 3
3       Return

with a resulting list of (1 5 2 4 3).

Somewhat ungolfed:

(load lib/utilities)

(def f
  (lambda (A B)
    (cons A
      (if (equal? A B)
        nil
        (f B
          ((if (less? A B) add2 sub2)
            A
            1))))))
\$\endgroup\$
2
\$\begingroup\$

APL+WIN, bytes 17, 13, 26

4 bytes saved thank to Adám plus 13 bytes see Jonah's comment

(⍴m)↑∊m,¨⌽m←(1↓m)+0,⍳-/m←⎕

Try it online! Courtesy of Dyalog Classic

Explanation:

m←(1↓m)+0,⍳-/m←⎕ Prompts high end of range followed by low end and generates vector

∊m,¨⌽m Reverse the vector, pair elements from both vectors and flatten.           

(⍴m)↑ Select the elements to the length of the original vector
\$\endgroup\$
  • \$\begingroup\$ Can you not replace [1.1] with ? And if you can't do that, then surely ∊m,¨⌽m works for the same byte count, no? \$\endgroup\$ – Adám Feb 14 at 11:40
  • \$\begingroup\$ @Adám No I cannot use ⍪ unless I already have a single row matrix which I would then have to transpose. This has knock on effects to the final selection. On the second point agreed but again a style point give same byte count. \$\endgroup\$ – Graham Feb 14 at 12:52
  • \$\begingroup\$ Doesn't monadic cause ⌽m to be a 1-column matrix, and then m, pairs up scalars of m with rows of ⌽m? Try! And ∊m,¨⌽m is surely shorter than m,[1.1]⌽m! \$\endgroup\$ – Adám Feb 14 at 14:43
  • \$\begingroup\$ @Adám From the manual: Join two arrays. The default for ⍪ is along the first dimension; the default for , is along the last dimension. There is no monadic option. ∊m,¨⌽m is indeed 4 bytes shorter. Thanks \$\endgroup\$ – Graham Feb 14 at 17:06
  • \$\begingroup\$ Your explanations are a bit behind. I would describe ∊m,¨⌽m as zipping and your last line has ,m which doesn't belong there. \$\endgroup\$ – Adám Feb 15 at 9:35
2
\$\begingroup\$

Ink, 45 bytes

=h(I,A)
{I<=A:{I} {I<A:{A} ->h(I+1,A-1)}}->->

(I don't think there's an online interpreter for Ink, sorry)
Try it online!

Defines a stitch called h, which takes two arguments I and A, which are the bounds of the range.

Outputs by printing values, separated by spaces, to stdout.

Explanation

=h(min, max) // Define the stitch.
{min <= max:{min}/* print min unless it's greater than max */{min < max: {max} /*Also print max if it's greater than min*/->h(min+1, max-1)/*Then divert, with the arguments changed*/}}
->-> // If we didn't divert earlier, divert to wherever the stitch was called from
\$\endgroup\$
2
\$\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\$
1
\$\begingroup\$

C# (.NET Core), 66 bytes

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

Try it online!

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

Haskell, 52 bytes

x?y=take(y+1-x).map head$iterate(reverse.tail)[x..y]

Try it online!

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

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

void a(int i,int j){Write((j-i)%2==0?i++:j--);if(i<=j)a(i,j);}

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ I think you need a separator. \$\endgroup\$ – Jonathan Frech Feb 13 at 19:48
1
\$\begingroup\$

Gol><>, 22 bytes

IIT}:nP}:nM2K(?t2K=?h;

Fixed!!! It had a major bug where it would sometimes append a zero when not necessary, but no longer!

Try it online!

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

Jelly, 6 bytes

rạṂ¥Þ,

Try it online!

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

Charcoal, 17 bytes

≔…·NNθWθ«≔⮌θθ⟦I⊟θ

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

≔…·NNθ

Create an inclusive range between the two inputs.

Wθ«

Repeat until it is empty.

≔⮌θθ

Reverse it.

⟦I⊟θ

Remove the last element and print it on its own line.

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

Perl 6, 32 bytes

{flat($_ Z [R,] $_)[^*/2]}o&[..]

Try it online!

Not too complicated, but there's a couple of tricks that help make the program shorter

Explanation:

{                        }o&[..]   # Convert the two inputs to a range
      $_ Z [R,] $_                 # Zip the range with its reverse
 flat(            )                # Flatten
                   [^*/2]          # And take the first half of the elements
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 39 37 bytes

f=a=>b=>a+[,a-b?f(b)(a<b?a+1:a-1):[]]

Try it online!

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

F# (.NET Core), 69 67 bytes

Translation of @nimi's answer.

fun a b->let rec h=function|a::b->[a]@h(List.rev b)|n->n in h[a..b]

Try it online!

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

PHP, 93 92 81 bytes

Standalone program, 81 bytes:

for($a=range($argv[1],$argv[2]);$a;)echo$x++%2?array_pop($a):array_shift($a),' ';

Try it online!

As a function, 92 bytes:

function($l,$h){for($a=range($l,$h);$a;)$b[]=$x++%2?array_pop($a):array_shift($a);return$b;}

Try it online!

function ( $l, $h ) {
    for( $a = range( $l, $h ); $a; ) {
        $b[] = $x++ % 2 ? array_pop( $a ) : array_shift( $a );
    }
    return $b;
}

Well, I thought it was a worth-trying idea. Perhaps in a more succinct language, this would work better. The Golf is not strong with this one.

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

Shortcuts for iOS, 20 Actions, 4 KB

Shortcuts is a visual scripting language, so the code is linked as a screenshot and download.

Screenshot (very tall) / Shortcut iCloud link

How it works:

getVariable (input.s)
if Equals (input.s)

This tests if input.s exists. input.s will be nothing if it does not exist. In shortcuts, nothing does not equal itself.

otherwise

There is no way to test for not equal in shortcuts other than using the else side of an if statement

dictionary {a:input.a, b:input.b, c:1}
setVariable (input)

To set a single key in a dictionary, you need to get the variable, set dictionary value, and re-set the variable. Creating a new dictionary here saves one action but takes more bytes. I am optimizing for actions here.

getVariable (input.a)
if Equals (input.b)
  getVariable(input.a)
otherwise

If both a and b are the same, this range only has one value. Values passed to otherwise are returned by End, similar to how ternary operators work in many languages.

number 0
calculate - (input.s)
getVariable (input.a)
calculate + (input.s)

No set variable is required because instead, magic variables are used to get the values from the calculate actions

dictionary{a: input.b, b:(Calculation Result), c: (Calculation Result)}

The two calculation results refer to different actions. The first to the a+s, and the second to the 0-s.

runShortcut ch-arrangement

Run this shortcut again with the new input and return the result.

To run, pass a dictionary containing a and b to the shortcut. Output is the list as a string (comma seperated). Screenshot / Link

There is no online interpreter for this. You need an iOS device and the Shortcuts app.

Logic from @ovs's javascript answer

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

Clojure, 62 bytes

#(distinct(let[r(range %1(inc %2))](interleave r(reverse r)))

Try it online!

Wow Clojure is a terrible golfing language. Still fun though.

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

VBA (Excel), 62 bytes

Using immediate window and [a1] and [a2] as input.

a=[a1]:b=[a2]:For x=0To(b-a)/2:?a+x &IIf(b-x=a+x,"",b-x);:Next
\$\endgroup\$
1
\$\begingroup\$

J, 23 bytes

[:(#$],@,.|.)[+i.@>:@-~

Try it online!

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

C (gcc), 46 bytes

A recursive function, call as f(low, high). As an extra 0-byte bonus, if you call f(high, low) the opposite arrangement is produced.

f(x,y){printf("%i ",x);x-y&&f(y,x+1-2*(x>y));}

Try it online!

Degolf

f(x,y)
{
  printf("%i ",x); // Print the value of x
  x-y&& // If x-y == 0, the && operator shorts and the
        // recursion ends.
    f(y,x+1-2*(x>y)); // Adjust x by 1 towards y, and
                      // recurse with x and y swapped.
}
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 54 53 52 bytes

  • Saved a byte two bytes thanks to Rogem.
s=1;f(x,y){printf("%d ",s*x),s=x-y?f(-y,~x,s=-s):1;}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ @Rogem Thank you again. \$\endgroup\$ – Jonathan Frech Feb 17 at 16:14
1
\$\begingroup\$

C (compiled with VC++ (Visual Studio 2017)) 264bytes

#include "stdafx.h"
void f(int l,int u){for(int t=1,h=0,H=0,i=0;i<u-l+1;i++,t^=1)printf("%d ",t?l+h++:u-H++);}void main(){f(1,5);}

choosing other Compiler may eliminate the Need for the include but vs2017 won't let me ommit it w/o Errors. the idea is to just use variables to Keep track of how many numbers have to be added to the Minimum or have to be subtracted from the maximum (2seperate variables) another variable is used to Keep track of from where the value has to be taken from front or from end. Setting it to 1 means lowest bit is set xor-ing it with 1 makes it toggle. i run a loop with the amount of iterations it takes to solve the Problem. inside the printf i use the Array Bounds and my variables to generate the number needed and increment my helper variables all at once. using the ternary Operator exp?then:else saves a few Bytes as it replaces a if-else Statement. further saving come through use of multiple variables defined in the for loop instead of only one (typically i) and putting the xor in the loop Header removes the Need for curly braces.

every Thing else i did is ommit spaces and linebreaks where possible and only use 1 character variable names and omitting ()s where ever possible

\$\endgroup\$
  • \$\begingroup\$ tested only with Bounds 1 and 5 but should work w/ everything else as well \$\endgroup\$ – der bender Feb 17 at 23:37
1
\$\begingroup\$

Java 8 (JDK): 113, 98, 124 bytes

(l,h)->{String s="";while(h>=l)s+=l+++" "+h--+" ";return s.substring(0,s.length()-(l-h==2?(l+(l<0?".":"")).length()+2:1));};

Thanka to Sriotchilism O'Zaic and Embodiment of Ignorance for saving me 15 bytes! Unfortunately those bytes were used to fix a bug Jo King mentioned.
Try it online

My first every golf code submission. Code is a functional interface that takes 2 integers and builds a string from those integers. The substring hack at the end hides a little quirk that duplicates the last element of the "array." Probably not the best solution, but for my first ever submission, I think I did well :)

\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! I haven't programmed very much in java, but this is a lambda right? Would it maybe be shorter to return the result rather than output it? System.out.print seems very long. \$\endgroup\$ – Sriotchilism O'Zaic Mar 5 at 3:52
  • \$\begingroup\$ Also, you can golf two bytes by removing the parens around l++ and h++. Try it online! \$\endgroup\$ – Embodiment of Ignorance Mar 5 at 3:53
1
\$\begingroup\$

><>, 20 bytes

:{:&=?v:1+&}
  oanr/

Try it online!

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

SNOBOL4 (CSNOBOL4), 95 bytes

	A =INPUT
	B =INPUT
L	OUTPUT =LE(A,B) A	:F(END)
	OUTPUT =GT(B,A) B
	A =A + 1
	B =B - 1	:(L)
END

Try it online!

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

1. Python 3.5, 123 bytes

Script takes two params: interval from, interval to.

from sys import*;v=[*range(int(argv[1]),int(argv[2])+1)];o=[]
for i in range(len(v)):v.reverse();o.append(v.pop())
print(o)

example:

$ ./script.py 1 5
[1, 5, 2, 4, 3]

$ ./script.py -5 6
[-5, 6, -4, 5, -3, 4, -2, 3, -1, 2, 0, 1]

Explanation

# create range input params
v=[*range(int(argv[1]),int(argv[2])+1)]

# define ampty output array
o=[]

# loop input-array-lenght times
for i in range(len(v)):

    # reverse input array
    v.reverse()

    # append last input element to output
    o.append(v.pop())

# print output array
print(o)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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