Interleave numbers from 1 to n, with the same numbers reversed

A simple one:

Take a positive integer n less than 1000, and output the integers from 1 to n interleaved with the integers from n to 1. You must concatenate the numbers so that they appear without any delimiters between them.

Test cases:

n = 1
11

n = 4
14233241

n = 26
12622532442352262172081991810171116121513141413151216111710189198207216225234243252261

n = 100
110029939849759669579489399210911190128913881487158616851784188319822081218022792378247725762675277428732972307131703269336834673566366537643863396240614160425943584457455646554754485349525051515052495348544755465645574458435942604161406239633864376536663567346833693270317130722973287427752676257724782379228021812082198318841785168615871488138912901191109299389479569659749839921001


This is so the shortest submission in bytes in each language wins. Explanations are encouraged.

JavaScript (ES6), 30 bytes

f=(n,k=1)=>n?f(n-1,k+1)+n+k:''


How?

This is pretty straightforward but it's worth noting that the string is built from tail to head. An empty string at the beginning is appended last and allows the coercion of the final result to a string to happen.

Below is the detail of the recursion for f(4):

f(4) =                                            // initial call
f(4, 1) =                                         // applying the default value to k
f(3, 2) + 4 + 1 =                                 // recursive call #1
(f(2, 3) + 3 + 2) + 4 + 1 =                       // recursive call #2
((f(1, 4) + 2 + 3) + 3 + 2) + 4 + 1 =             // recursive call #3
(((f(0, 5) + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =   // recursive call #4
((('' + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =        // n = 0 --> end of recursion
'' + 1 + 4 + 2 + 3 + 3 + 2 + 4 + 1 =              // final sum
'14233241'                                        // final result


Test cases

f=(n,k=1)=>n?f(n-1,k+1)+n+k:''

console.log(f(1))
console.log(f(4))
console.log(f(26))
console.log(f(100))

Python 2, 46 bytes

lambda n:''.join(x+1+n-xfor x in range(n))


Thanks to ovs for 4 bytes

Try it online!

Explanation:

lambda n:''.join(x+1+n-xfor x in range(n))
lambda n:                                      # anonymous lambda taking one parameter n
x+1+n-x                   # x is repr(x) which is equivalent to str(x) for integers less than INT_MAX
for x in range(n)  # integers x in [0, n)

• Two bytes more in Python 3: f'{x}{n-~-x}' May 30 '17 at 11:02
• @L3viathan That's a new feature added in 3.6.
– user45941
May 30 '17 at 11:03
• Python 3.6 is not Python 3? May 30 '17 at 11:04
• lambda n:''.join('x+1'+'n-x'for x in range(n)) for 46 bytes .(replace the ' in the list comprehension with backticks)
– ovs
May 30 '17 at 11:53
• @ovs hey, you can escape the backtick -> \x+1\ renders to x+1
– Rod
May 30 '17 at 12:29

-5 thanks to Ørjan Johansen

f n=do a<-[1..n];[a,n-a+1]>>=show


Try it online!

• (1) A do expression is shorter than >>= plus a lambda. (2) However, the shows can be combined by using >>=show. May 30 '17 at 12:18

Bash, 25 bytes

printf %sseq $1 -1 1|nl  Try it online! Prints decreasing sequence, number lines increasing and printf joins lines Space delimited, 20 bytes : seq$1 -1 1|nl|xargs

• if that is not acceptable i can change it for seq $1 -1 1|nl|tr -d ' \n\t' 8 bytes more May 30 '17 at 12:24 • The 20 byte submission is invalid. My upvote is for the 25 byte submission. May 31 '17 at 0:03 • As Digital Trauma noted, the 20-byte solution is invalid. May 31 '17 at 11:49 • time printf %s'seq 1000000 -1 1|nl'; grep name /proc/cpuinfo real 0m7.985s user 0m6.092s sys 0m0.392s model name : Intel(R) Pentium(R) D CPU 3.00GHz model name : Intel(R) Pentium(R) D CPU 3.00GHz May 31 '17 at 14:06 R, 35 bytes n=scan();cat(rbind(1:n,n:1),sep="")  Try it online rbind(1:n,n:1) creates a 2 row matrix with 1 to n in the first row and n to 1 in the second. The cat function collapses this matrix, reading down each column. • Note that this only works in interactive mode, and requires the user to enter n on the command line (instead of passing via stdin). May 30 '17 at 19:54 • @ssdecontrol Yes, I think that's usually allowed, but I'm fairly new here, could be wrong. May 30 '17 at 20:16 • I think it's generally acceptable, but NB, to run it properly in TIO you have to put the input(s) in the Footer field (and it's always good to include a link!) tio.run/nexus/… May 30 '17 at 20:28 05AB1E, 6 5 bytes Saved a byte using the new interleave built-in as suggested by rev LÂ.ιJ  Try it online! Explanation L # range [1 ... input] Â # create a reversed copy .ι # interleave the lists J # join  • A user by the name of rev suggested LÂ.ιJ. Mar 6 '19 at 22:20 • @JonathanFrech: I know the consensus now is that we can use features newer than the challenge, but I'm usually hesitant to edit old answers because a new built-in completes the challenge better. There are so many answers in all that could be improved that way :) Mar 7 '19 at 7:10 • Well, I only was the messenger; possible @rev should post their own answer. Mar 7 '19 at 7:56 • @JonathanFrech: I didn't mean it as a reproach. Rev did it correctly when he suggested the edit as it is better to edit an existing answer than post a new one whenever a new built-in is made. I really should get better at fixing old answers, at least when suggestions are made. Mar 7 '19 at 8:10 CJam, 10 bytes ri,:)_W%]z  Try it online! Explanation ri e# Read input and convert to integer N. , e# Turn into range [0 1 ... N-1]. :) e# Increment to get [1 2 ... N]. _W% e# Duplicate and reverse the copy. ] e# Wrap both in an array to get [[1 2 ... N] [N ... 2 1]] z e# Transpose to get [[1 N] [2 N-1] ... [N-1 2] [N 1]] e# This list is printed implicitly at the end of the program, e# but without any of the array structure (so it's essentially flattened, e# each number is converted to a string and then all the strings e# are joined together and printed).  Ruby, 29 bytes ->n{n.times{|x|$><<x+1<<n-x}}


Explanation:

->n{n.times{|x|                # x in range [0..n-1]
$><< # output on console x+1<<n-x}} # x+1, then n-x  Try it online! Whitespace, 71 bytes   Try it online! Explanation sssn ; push 0 - seed the stack with 0 (this will be our 1->n counter, a) sns ; dup tntt ; getnum - read n (stored on the heap) sns ; dup ttt ; retr - pull n onto the stack (this will be our n->1 counter, b) nssn ; label 'loop' snt ; swap - bring a to the top ssstn ; push 1 tsss ; add - increment a sns ; dup tnst ; putnum - output a as a number snt ; swap - bring b to the top sns ; dup tnst ; putnum - output b as a number ssstn ; push 1 tsst ; sub - decrement b sns ; dup ntstn ; jez 'exit' if b is 0 nsnn ; jmp 'loop'  The first couple of instructions are needed to set up the stack correctly, Whitespace's input commands write to the heap so we need to copy b (the input value) back onto the stack. We start with a = 0 since it is shorter to declare 0 instead of 1 (saves a byte) and we only need to reorder the increment instruction to cope. After that we just loop and increment a, output a, output b, decrement b, until b reaches 0 (checked after the decrement). • this could be much more golfed if you removed all that trailing whitespace :P – cat Jun 1 '17 at 13:59 Haskell, 6548 47 bytes 1 byte saved thanks to Laikoni: f n=show=<<(\(l,r)->[l,r])=<<zip[1..][n,n-1..1]  6 bytes saved thanks to nimi: f n=show=<<(\(l,r)->[l,r])=<<zip[1..n][n,n-1..1]  Previous answer and explanation: f n=concatMap show$concatMap(\(l,r)->[l,r])(zip[1..n][n,n-1..1])


There's already a better Haskell answer here, but I'm new to both Haskell and code golfing, so I may as well post it :)

This function zips the list [1..n] with its reverse, resulting in a list of tuples.

[(1,n),(2,n-1),(3,n-2)..(n,1)]


Then it uses concatMap to map a lambda to this list of tuples that results in a list of lists...

[[1,n],[2,n-1],[3,n-2]..[n,1]]


...and concatenates it.

[1,n,2,n-1,3,n-2..n,1]


Then a final concatMap maps show to the list and concatenates it into a single string.

f 26 "12622532442352262172081991810171116121513141413151216111710189198207216225234243252261"

• The infix function =<< is the same (within the list monad) as concatMap: f n=show=<<(\(l,r)->[l,r])=<<zip[1..n][n,n-1..1].
– nimi
May 30 '17 at 14:37
• 1) Your current solution is only 48 bytes. 2) You can drop the n in [1..n]: Try it online! May 31 '17 at 19:34
• 1) Dang off-by-one errors... 2) Good call! May 31 '17 at 19:59

Pyth, 7 bytes

jksC_BS


Try it online: Demonstration

Explanation:

jksC_BSQ   implicit Q (=input number) at the end
SQ   create the range [1, ..., Q]
_B     bifurcate by inversion, this gives [[1, ..., Q], [Q, ..., 1]]
sC       zip and flatten result
jk         join to a string


Octave, 29 bytes

@(n)printf("%d",[1:n;n:-1:1])


Try it online!

• My implementation was so, so much longer! Nice! =) May 30 '17 at 18:56

Perl 6, 20 bytes

{[~] 1..*Z~($_...1)}  Test it With an input of 100000 this takes roughly 10 seconds, including compilation and printing the output. Expanded: { # bare block lambda with implicit parameter ｢$_｣

[~]            # reduce using concatenation operator ｢&infix:«~»｣
# (shorter than ｢join '',｣)

1 .. *       # Range from 1 to infinity

Z~           # zip using concatenation operator

( $_ ... 1 ) # deduced sequence starting at the input # going down to 1 }  The Z~ needs the ~ because otherwise it generates a list of lists which will stringify with spaces. There is no need to limit the Range starting at 1, because Z stops when any of the input lists run out. This saves two bytes (a space would be needed after $_)

Java 61 bytes

(int n)->{for(int i=0;i<n;System.out.print(i+1+""+(n-i++)));}

• Also, welcome to PPCG! :) May 30 '17 at 15:39
• We allow anonymous functions, so (int n)->{//for loop} should work here. May 30 '17 at 15:39
• Is that better? May 30 '17 at 15:45
• Yep! You can potentially put your System.out.print() in the last statement of the for loop, but it gets complicated because you are using i twice (and you need to increment it in the expression). May 30 '17 at 15:48
• I put the print inside the loop and incremented i at the last possible place then checked it with the Test cases to make sure it worked, thanks @NathanMerrill May 30 '17 at 15:58

Jelly, 5 bytes

RṚĖVV


Try it online!

How it works

RṚĖVV  Main link. Argument: n

R      Range; yield [1, ..., n].
Ṛ     Reverse; yield [n, ..., 1].
Ė    Enumerate; yield [[1, n], ..., [n, 1]].
V   Eval; convert each flat array to a string, interpret it as a Jelly program,
and yield the output. This concatenates the integers in each pair, yielding
a flat array of integers
V  Repeat the previous step, concatenating the intgegers from before.


Röda, 21 19 bytes

{seq 1,_<>seq _1,1}


Try it online!

This is an anonymous function that takes input from the stream.

Explanation

{seq 1,_<>seq _1,1}               Anonymous function, takes integer n from the stream
<>                        Interleave
seq 1,_                            the range 1 .. n with
seq _1,1                  the range n .. 1


Clojure, 61 bytes

#(let[a(range 1(+ 1 %))](apply str(interleave a(reverse a))))


Literally does what is asked. I believe it can be outgolfed by a less trivial solution.

Aceto, 25 22 bytes

)&
pX=
(pl0
id@z
r}Z)


Explanation:

We read an integer and put it on two stacks.

id
r}


On one, we call range_up (Z), on the other range_down (z), then we set a catch mark to be able to return to this place later:

  @z
Z)


We then check if the current stack is empty and exit if so:

 X=
l0


Otherwise, we print from both stacks and jump back to the catch mark:

)&
p
(p


R, 41 bytes

pryr::f(for(i in 1:x){cat(i);cat(x-i+1)})


pryr::f() creates a function that takes one input. Loops over 1:x and prints each element of 1:x along with each element of x:1. Prints to STDOUT.

• +1, nice use of pryr May 30 '17 at 19:48
• @ssdecontrol its pretty much staple replacement of function(x) :)
May 30 '17 at 19:57

Brachylog, 10 9 bytes

⟦₁g↔ᶻczcc


Try it online!

Explanation

⟦₁           [1, …, Input]
g↔ᶻc       [[1, …, Input],[Input, …, 1]]
z      Zip
cc    Concatenate twice


MATL, 1311 9 bytes

2 bytes saved thanks to @Luis

:tPv1eVXz


Try it at MATL Online

Explanation

        % Implicitly grab input as a number, N
:       % Create an array from 1..N
tP      % Create a reversed copy
v       % Vertically concatenate the two
1e      % Reshape it into a row vector
V       % Convert to a string
Xz      % Remove whitespace and implicitly display

• @LuisMendo Ah! I thought there was a function that removed whitespace but couldn't find it. Thanks! May 30 '17 at 13:09

PHP, 3635 29 bytes

for(;$argn;)echo++$i,$argn--;  Saved one byte thanks to Jörg Hülsermann. Saved six bytes thanks to Christoph. • Uhm... for(;$argn;)echo++$i,$argn--; ? May 30 '17 at 13:13

Scala, 43 bytes

It's not the best but it's my first code golf.

n=>1.to(n).foldLeft("")((s,x)=>s+x+(n-x+1))


V, 20 bytes

ywo1@"­ñykPjñkògJ


Try it online!

Explain:

yw                    ' Copy the input number (for looping later)
o1                 ' Insert a 1 under the input (on a newline)
@"               ' [Copy register] number of times
­ñ      ñ       ' Do the thing inside of this loop
ykP           ' Copy the current line and line above it, and paste above both
j        ' decrement the current (top) number, and increment the one below
k      ' Go to the top line
ògJ   ' recursively join all of the lines


Cubix, 17 bytes

....1I>sO)su.@?(O


Try it online!

cubified:

    . .
. .
1 I > s O ) s u
. @ ? ( O . . .
. .
. .


Pushes 1, reads in the input (I), then enters the loop which swaps the top of the stack, outputs it, increments, swaps, outputs the top of the stack, decrements, and stops if the top of the stack is 0.

K (ngn/k), 16 bytes

{,//\$r,'|r:1+!x}


Try it online!

• r,'|r: -> +|:\
– ngn
Nov 9 '18 at 13:47

MathGolf, 5 bytes

{îkï-


Try it online!

Explanation:

{      Run a for loop over implicit input
î     Push 1 based index of loop
k    Push inputted number
ï-  Subtract 0 based index of loop
Implicitly output all this joined together

• I've been able to find 13 programs of length 5 which yield the same result: ╒{ïí,, ╒{ïk,, ╒{íï-, ╒{kï-, ╒{┐í,, ╒{┐k,, ╒x{î\ , {îïí,, {îïk,, {îíï-, {îkï-, {î┐í,, {î┐k,. However, I have not been able to find any program of length 4 or less. I haven't done a full search, but it is very probable that 5 bytes is optimal for MathGolf.
– maxb
Mar 7 '19 at 9:53

Common Lisp, 63 54 bytes

(lambda(n)(dotimes(i n)(format t"~a~a"(1+ i)(- n i))))


Try it online!

Mouse-2002, 32 30 bytes

-2 moved conditional to start of loop (z.^ ... ) instead of (... z.0>^)

?n:n.z:(z.^a.1+a:a.!z.!z.1-z:)


Try it online!

Explanation:

?n:                                 ~ get input and store in n
n.z:                             ~ copy n into z
(z.^                         ~ stop if z equals 0
a.1+a:                   ~ add 1 to a
a.!                ~ print a
z.!             ~ print z
z.1-z:)      ~ substract 1 from z


Actually, 9 bytes

R;R@Z♂iεj


Explanation:

R;R@Z♂iεj
R          range(1, n+1)
;R        duplicate and reverse
@Z      swap and zip
♂i    make 1D
εj  join with empty string