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

34

3

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.

Stewie Griffin

Posted 2017-05-30T10:32:31.487

Reputation: 43 471

Answers

16

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

Arnauld

Posted 2017-05-30T10:32:31.487

Reputation: 111 334

10

Python 2, 46 bytes

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

Thanks to ovs for 4 bytes

Try it online!

Explanation:

lambda n:''.join(`x+1`+`n-x`for 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)

Mego

Posted 2017-05-30T10:32:31.487

Reputation: 32 998

1Two bytes more in Python 3: f'{x}{n-~-x}' – L3viathan – 2017-05-30T11:02:07.203

2@L3viathan That's a new feature added in 3.6. – Mego – 2017-05-30T11:03:27.083

1Python 3.6 is not Python 3? – L3viathan – 2017-05-30T11:04:20.520

1@L3viathan It is, but it's a specific version. Python 3.5 and below don't have that string interpolation feature. – Mego – 2017-05-30T11:04:59.910

It is the most recent version. Generator comprehensions, which you use, were added in Python 2.4, Python 2.3 and below don't have that feature, but you still categorize your answer as "Python 2". – L3viathan – 2017-05-30T11:06:51.590

1@L3viathan That's because Python 2.7 is in wide use. The same cannot be said for 3.6 yet. For example, the Ubuntu Main repo only has 3.5. 2.4 was released in 2004; 3.6 was released 5 months ago. There's a stark difference. – Mego – 2017-05-30T11:10:32.663

6lambda n:''.join('x+1'+'n-x'for x in range(n)) for 46 bytes .(replace the ' in the list comprehension with backticks) – ovs – 2017-05-30T11:53:59.857

6@ovs hey, you can escape the backtick -> \\`x+1\``` renders to \x+1`` – Rod – 2017-05-30T12:29:19.373

8

-5 thanks to Ørjan Johansen

Haskell, 33 bytes

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

Try it online!

bartavelle

Posted 2017-05-30T10:32:31.487

Reputation: 1 261

3(1) A do expression is shorter than >>= plus a lambda. (2) However, the shows can be combined by using >>=show. – Ørjan Johansen – 2017-05-30T12:18:59.750

7

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.

user2390246

Posted 2017-05-30T10:32:31.487

Reputation: 1 391

1Note that this only works in interactive mode, and requires the user to enter n on the command line (instead of passing via stdin). – shadowtalker – 2017-05-30T19:54:33.513

@ssdecontrol Yes, I think that's usually allowed, but I'm fairly new here, could be wrong. – user2390246 – 2017-05-30T20:16:26.087

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!) https://tio.run/nexus/r#@59nW5ycmKehaZ2cWKJRlJSZl6JhaJWnk2dlqKlTnFpgq6Sk@d/0PwA

– Giuseppe – 2017-05-30T20:28:06.173

7

Bash, 25 bytes

printf %s`seq $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

marcosm

Posted 2017-05-30T10:32:31.487

Reputation: 986

if that is not acceptable i can change it for seq $1 -1 1|nl|tr -d ' \n\t' 8 bytes more – marcosm – 2017-05-30T12:24:28.767

1The 20 byte submission is invalid. My upvote is for the 25 byte submission. – Digital Trauma – 2017-05-31T00:03:27.180

As Digital Trauma noted, the 20-byte solution is invalid. – Erik the Outgolfer – 2017-05-31T11:49:51.913

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 – marcosm – 2017-05-31T14:06:48.223

6

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

Emigna

Posted 2017-05-30T10:32:31.487

Reputation: 50 798

A user by the name of rev suggested LÂ.ιJ.

– Jonathan Frech – 2019-03-06T22:20:43.717

@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 :) – Emigna – 2019-03-07T07:10:20.270

Well, I only was the messenger; possible @rev should post their own answer. – Jonathan Frech – 2019-03-07T07:56:58.973

@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. – Emigna – 2019-03-07T08:10:45.700

4

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).

Martin Ender

Posted 2017-05-30T10:32:31.487

Reputation: 184 808

4

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!

G B

Posted 2017-05-30T10:32:31.487

Reputation: 11 099

4

Haskell, 65 48 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"

Dan Ambrogio

Posted 2017-05-30T10:32:31.487

Reputation: 141

2The 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 – 2017-05-30T14:37:27.743

1

>

  • Your current solution is only 48 bytes. 2) You can drop the n in [1..n]: Try it online!
  • – Laikoni – 2017-05-31T19:34:26.477

    >

  • Dang off-by-one errors... 2) Good call!
  • < – Dan Ambrogio – 2017-05-31T19:59:32.697

    4

    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).

    Ephphatha

    Posted 2017-05-30T10:32:31.487

    Reputation: 581

    this could be much more golfed if you removed all that trailing whitespace :P – cat – 2017-06-01T13:59:16.097

    3

    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
    

    user41805

    Posted 2017-05-30T10:32:31.487

    Reputation: 16 320

    3

    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
    

    Jakube

    Posted 2017-05-30T10:32:31.487

    Reputation: 21 462

    3

    Octave, 29 bytes

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

    Try it online!

    rahnema1

    Posted 2017-05-30T10:32:31.487

    Reputation: 5 435

    1My implementation was so, so much longer! Nice! =) – Stewie Griffin – 2017-05-30T18:56:02.453

    3

    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 $_)

    Brad Gilbert b2gills

    Posted 2017-05-30T10:32:31.487

    Reputation: 12 713

    3

    Java 61 bytes

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

    cheemcheem

    Posted 2017-05-30T10:32:31.487

    Reputation: 49

    2Also, welcome to PPCG! :) – Stewie Griffin – 2017-05-30T15:39:20.507

    We allow anonymous functions, so (int n)->{//for loop} should work here. – Nathan Merrill – 2017-05-30T15:39:44.563

    Is that better? – cheemcheem – 2017-05-30T15:45:31.087

    2Yep! 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). – Nathan Merrill – 2017-05-30T15:48:16.030

    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 – cheemcheem – 2017-05-30T15:58:08.157

    don't need the parens around int n iirc. Or int for that matter. – Cyoce – 2017-06-07T07:30:50.643

    3

    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.
    

    Dennis

    Posted 2017-05-30T10:32:31.487

    Reputation: 196 637

    2

    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.

    See it online

    cliffroot

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 080

    2

    PHP, 36 35 29 bytes

    for(;$argn;)echo++$i,$argn--;
    

    Saved one byte thanks to Jörg Hülsermann.
    Saved six bytes thanks to Christoph.

    user63956

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 571

    3Uhm... for(;$argn;)echo++$i,$argn--; ? – Christoph – 2017-05-30T13:13:39.210

    2

    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
    

    L3viathan

    Posted 2017-05-30T10:32:31.487

    Reputation: 3 151

    2

    Brachylog, 10 9 bytes

    ⟦₁g↔ᶻczcc
    

    Try it online!

    Explanation

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

    Fatalize

    Posted 2017-05-30T10:32:31.487

    Reputation: 32 976

    2

    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.

    JAD

    Posted 2017-05-30T10:32:31.487

    Reputation: 2 898

    +1, nice use of pryr – shadowtalker – 2017-05-30T19:48:10.987

    @ssdecontrol its pretty much staple replacement of function(x) :) – JAD – 2017-05-30T19:57:28.260

    2

    MATL, 13 11 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
    

    Suever

    Posted 2017-05-30T10:32:31.487

    Reputation: 10 257

    @LuisMendo Ah! I thought there was a function that removed whitespace but couldn't find it. Thanks! – Suever – 2017-05-30T13:09:39.913

    2

    V, 20 bytes

    ywo1@"­ñykPjñ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
    

    nmjcman101

    Posted 2017-05-30T10:32:31.487

    Reputation: 3 274

    2

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

    Phoenix

    Posted 2017-05-30T10:32:31.487

    Reputation: 151

    2

    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.

    Giuseppe

    Posted 2017-05-30T10:32:31.487

    Reputation: 21 077

    2

    Common Lisp, 63 54 bytes

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

    Try it online!

    Renzo

    Posted 2017-05-30T10:32:31.487

    Reputation: 2 260

    2

    K (ngn/k), 16 bytes

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

    Try it online!

    Thaufeki

    Posted 2017-05-30T10:32:31.487

    Reputation: 421

    r,'|r: -> +|:\ – ngn – 2018-11-09T13:47:52.897

    2

    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
    

    Jo King

    Posted 2017-05-30T10:32:31.487

    Reputation: 38 234

    1I'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 – 2019-03-07T09:53:15.683

    2

    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
    

    MooseOnTheRocks

    Posted 2017-05-30T10:32:31.487

    Reputation: 191

    1

    Actually, 9 bytes

    R;R@Z♂iεj
    

    Try it online!, or run all test cases

    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
    

    Mego

    Posted 2017-05-30T10:32:31.487

    Reputation: 32 998

    1

    QBIC, 18 bytes

    [:|Z=Z+!a$+!b-a+1$
    

    Explanation

    [:|       FOR a = 1 to n
    Z=Z+      Add to Z$ 
    !b$+      a cast of the loop counter as string
    !b-a+1$   and a cast of (n+1) minus the loop counter to string
              Z$ is printed implicitly at the end of QBIC
    

    steenbergh

    Posted 2017-05-30T10:32:31.487

    Reputation: 7 772

    1

    Mathematica, 36 32 bytes

    Row@Riffle[x=Range@#,Reverse@x]&
    

    thanks Martin

    J42161217

    Posted 2017-05-30T10:32:31.487

    Reputation: 15 931

    #+1-x is more efficient than Reverse@x. ------- Note: Row does not even make it a string, just a formatting. It looks identical to a string on some platforms, but it show as multiplication sign between on Wolfram sandbox. However it takes less bytes than ToString/@(""<>...) or ""<>ToString/@.... – user202729 – 2017-06-10T15:32:33.207

    1

    CJam, 13 12 bytes

    1 byte removed thanks to Martin Ender

    ri:X{_)X@-}%
    

    Try it online!

    Explanation

    ri               e# Read integer n
      :X             e# Copy n into variable X
         {     }%    e# Map over the array [0 1 2 ... n-1]
          _          e# Duplicate
           )         e# Add 1
            X        e# Push n
             @       e# Rotate
              -      e# Subtract
    

    Luis Mendo

    Posted 2017-05-30T10:32:31.487

    Reputation: 87 464

    1

    Perl 5, 28 bytes

    27 bytes code + 1 byte for -a.

    map{print$_,"@F"+1-$_}1..$_
    

    Try it online!

    Dom Hastings

    Posted 2017-05-30T10:32:31.487

    Reputation: 16 415

    1

    Braingolf v0.7, 18 bytes [non-competing]

    VR.MUvU&,R{vMR}>&_
    

    Try it online!

    Explanation:

    VR.MUvU&,R{vMR}>&_  Implicit input of n to stack
    VR                  Create new stack then return to main
      .M                Duplicate n and move duplicate to new stack
        U               Replace stack with 1-n, where n is last item on stack
         vU             Replace 2nd stack with 1-n
           &,           Reverse second stack
             R          Return to main
              {   }     Map loop, runs for each item in the stack
               vMR      Move to next stack, move last item to main stack
                   >    Cleanup after loop
                    &_  Print all items in stack with no delimiter
    

    Skidsdev

    Posted 2017-05-30T10:32:31.487

    Reputation: 9 656

    Did you just add the entire interpreter in the header in TIO? I guess that's why it's non-competing? – Stewie Griffin – 2017-05-30T19:02:19.000

    Yes I did, the language isn't on TIO yet, but that doesn't make it non-competing, it's nc because braingolf v0.7, which adds the {} loop, was released after the challenge was posted. – Skidsdev – 2017-05-30T21:52:00.177

    1

    Japt -P, 11 8 bytes

    Saved 2 byte thanks to @Shaggy

    õ í1õU)c
    

    Try it online!

    Explanation:

    õ í1õU)c
    õ              Range [1...Input]
      í            Pair with:
       1õU           Range [Input...1]  
          )c       Flatten   
    -P             Join into a string  
    

    Oliver

    Posted 2017-05-30T10:32:31.487

    Reputation: 7 160

    Use the -P flag to save a byte. Link

    – Shaggy – 2017-06-06T16:11:17.897

    @Shaggy Thanks! When I wrote it, I tried this and assumed it wasn't joining due to a bug.

    – Oliver – 2017-06-06T16:26:29.980

    18 bytes – Shaggy – 2018-11-06T17:48:38.343

    1

    Powershell, 37 bytes

    param($n)-join(1..$n|%{$_,($n-$_+1)})
    

    Danko Durbić

    Posted 2017-05-30T10:32:31.487

    Reputation: 10 241

    1

    Jelly, 6 bytes

    RżU$FV
    

    Try it online!

    Explanation:

             Example: n = 6
    R        Create a range from 1 to n             [1, 2, 3, 4, 5, 6]
      U$     and a reversed copy of that same range [6, 5, 4, 3, 2, 1]
     ż       and interleave them                    [ [1, 6], [2, 5, ... ]
        F    Flatten the list                       [1, 6, 2, 5, 3, 4 ...]
         V   And Eval: Jelly code consisting of only numbers would simply print those numbers,
    

    steenbergh

    Posted 2017-05-30T10:32:31.487

    Reputation: 7 772

    1

    Retina, 20 bytes

    .+
    $*__
    \B
    $.`$.'
    _
    
    

    Try it online! Includes test cases. Explanation: Each pair of numbers sums to n+1, so we convert n to unary and add 1. Then, we match between each pair of _s, counting the number of _s to the left and right. This generates the pairs of numbers. Finally we delete the _s now that they've served their purpose.

    Neil

    Posted 2017-05-30T10:32:31.487

    Reputation: 95 035

    1

    ><>, 16 12+3 = 19 15 bytes

    l:n}:n1-:?!;
    

    Input is expected on the stack, so +3 bytes for the -v flag.

    Thanks to @TealPelican for pointing out a very clever way to save 4 bytes by using the size of the stack itself - on the first iteration it'll be 1, then 2, then 3... That way, the first number in each pair manages itself, no manual incrementing required!

    Previous version:

    1:n1+$:n1-:?!;$!
    

    Try it online!

    Sok

    Posted 2017-05-30T10:32:31.487

    Reputation: 5 592

    1Surprisingly I came up with something fairly similar before checking the answers for ><> but you can save a few bytes by replacing the; 1+$ with } and then removing the final; $! at the end to come up with this; l:n}:n1-:?!; – Teal pelican – 2017-06-02T15:25:51.250

    ln:n1-::?!; – Jo King – 2018-11-06T21:40:05.130

    1

    Perl 5, 25 21 + 1 = 26 22 bytes

    Takes input from stdin, without a trailing newline.

    Runs with the -n flag:

    print++$x.$_--while$_
    

    4 bytes saved thanks to Dada.

    Chris

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 313

    It doesn't work for numbers greater than 9. That's because the precedence of . is higher than the one of +. Adding parenthesis around $_+1 would solve this. Also, you can remove the parenthesis around $_--. But even shorter, you can take the input without final newline (with echo -n for instance), and then you can do print++$x.$_--while$_. – Dada – 2017-06-01T08:01:06.543

    1

    C (gcc), 43 bytes

    a;f(n){for(a=1;n;a++)printf("%d%d",a,n--);}
    

    Try it online!

    Leaky Nun

    Posted 2017-05-30T10:32:31.487

    Reputation: 45 011

    1You can save a byte by putting the ++ on the a in the printf. – Ørjan Johansen – 2017-06-10T15:00:34.457

    1

    Python 3, 51 bytes

    lambda n:''.join("%d%d"%(x+1,n-x)for x in range(n))
    

    Try it online!

    Port of Mego's Python 2 answer.

    Leaky Nun

    Posted 2017-05-30T10:32:31.487

    Reputation: 45 011

    1

    Japt -mP, 8 6 bytes

    °Us+N´
    

    Try it

               :For each U in the range [0,input)
    °U         : Prefix increment U
      s        : Convert to a string
       +       : Append
        N´     :  Postfix decrement the (singleton) array of inputs
               :Implicitly join and output
    

    Shaggy

    Posted 2017-05-30T10:32:31.487

    Reputation: 24 623

    1

    C# (.NET Core), 53 bytes

    a=>{for(int i=0;++i<=a;)Console.Write(i+""+(a-i+1));}
    

    Try it online!

    Uses an Action delegate to pull in the input and not require a return.

    Ungolfed:

    a => {
        for(int i = 0; ++i <= a;)           // initialize i and increment until a
            Console.Write(i + "" + (a - i + 1));    // output i and "inverse" of i
                                                        // empty string required to set as string
                                                        // parentheses required because C# is dumb and can't figure out what a minus sign is supposed to do without them
    }
    

    Meerkat

    Posted 2017-05-30T10:32:31.487

    Reputation: 371

    1

    Forth (gforth), 41 bytes

    : f 1+ dup 1 do i 1 .r 1- dup 1 .r loop ;
    

    Try it online!

    Explanation

    Loops from 1 to n and outputs the index as well as n-index in a right-aligned space of size 1 (forces no space after output)

    Code Explanation

    : f               \ start new word definition
      1+ dup 1        \ set up arguments to loop from 1 to n
      do              \ start loop
        i 1 .r        \ output the index in a right-aligned space of size 1
        1- dup        \ subtract 1 from current value of n and duplicate
        1 .r          \ output new n in right-aligned space of size 1
      loop            \ end loop
    ;                 \ end word definition
    

    reffu

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 361

    1

    Kotlin, 52 50 bytes

    fun g(e:Int)=(1..e).forEach{print("$it${e-it+1}")}
    

    Try it online

    Older version, the one above also prints it, the one below produces a string.

    fun y(n:Int)=(1..n).joinToString(""){"$it${n-it+1}"}
    

    Try it online!

    J00LZ

    Posted 2017-05-30T10:32:31.487

    Reputation: 11

    1

    APL (Dyalog Unicode), 10 bytesSBCS

    (∊⍪,⌽)⍕¨∘⍳
    

    Try it online!

    Explanation:

    (∊⍪,⌽)⍕¨∘⍳  ⍝ Monadic function train
           ⍕¨∘⍳  ⍝ Generate integers from 1 to input, convert each to string
                 ⍝ Call this vector "X"
      ⍪          ⍝ "Table" X, making a single-column matrix
       ,⌽       ⍝ Reverse X and concatenate it with the above table
                 ⍝ This results in a two-column matrix with integers from
                 ⍝ 1 to N and N to 1 side-by-side
     ∊           ⍝ "Enlist" the above - left-to-right, top-to-bottom,
                 ⍝ recursively concatenate all items in the matrix
    

    voidhawk

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 796

    Don't forget to claim your bounty!

    – Adám – 2019-03-09T21:05:03.007

    here's a shorter one: ∊⍕¨⌽,⌸⌽⍳⎕ – ngn – 2019-03-14T12:00:35.433

    0

    AWK, 34 30 bytes

    {for(i=1;i<=$1;i++)printf i$1-i+1}

    {for(;i<$1;i++)printf i+1$1-i}
    

    Try it online!

    jmriego

    Posted 2017-05-30T10:32:31.487

    Reputation: 381

    could shave 4 with {for(;i<$1;i++)printf i+1$1-i} – marcosm – 2017-05-30T13:50:18.800

    0

    Clojure, 52 bytes

    #(apply str(mapcat(fn[i][(inc i)(- % i)])(range %)))
    

    Concatenates pair-wise integers (head and tail of the seq).

    NikoNyrh

    Posted 2017-05-30T10:32:31.487

    Reputation: 2 361

    0

    Python 2.7, 39 bytes

    x=''.join(`i+1`+`n-i`for i in range(n))
    

    Dat

    Posted 2017-05-30T10:32:31.487

    Reputation: 879

    4I think you must either use input or make this a lambda. Assuming the variable exists in the workspace is not acceptable I'm afraid. – Stewie Griffin – 2017-05-30T15:45:58.190

    0

    Pyke, 9 bytes

    SD_],sm`s
    

    Try it here!

    Blue

    Posted 2017-05-30T10:32:31.487

    Reputation: 26 661

    0

    Mathematica, 52 bytes

    As a traditional function:

    f[x_] := StringJoin[ToString /@ Riffle[Range[x], Reverse[Range[x]]]]
    

    As an anonymous function

    (x = Range[#]; StringJoin[ToString /@ Riffle[x, Reverse[x]]]) &
    

    As a code block that accepts the input in the variable n

    x = Range[n]; StringJoin[ToString /@ Riffle[x, Reverse[x]]]
    

    The code is pretty simple -- generate the list of integers with Range[], interleave this list (using Riffle[]) with a copy of the list that has been reversed, then convert all the integers to strings and concatenate them with StringJoin[].

    Could have done it in 30 bytes if we were allowed to leave the answer in the form of a list (thus, {1,4,2,3,3,2,4,1} rather than "14233241"). Also, in the hypothetical Mthmtca with short command names it would have been something like 21 bytes.

    Performance is tolerable for n <= 1,000,000. I didn't test past that.

    Michael Stern

    Posted 2017-05-30T10:32:31.487

    Reputation: 3 029

    1This should be a function that takes an integer argument, rather than having a 4 hardcoded. – Greg Martin – 2017-05-30T21:38:36.437

    This isn't golfed either, which makes it invalid – cat – 2017-06-01T01:34:38.647

    @cat if you think you can write it more concisely, please do so. If you can't, why do you think it's not golfed? – Michael Stern – 2017-06-01T03:29:45.763

    Yeah, f[x_]:=StringJoin[ToString/@Riffle[Range[x],Reverse[Range[x]]]], I think I counted the close braces right from my phone. Either way I know for a fact that MMA doesn't rely on whitespace, and I can say that as a communiry member – cat – 2017-06-01T10:53:00.720

    2None of these are 52 bytes, even with whitespace stripped. I get 56 bytes for the middle one (the last one not being valid). – Ørjan Johansen – 2017-06-01T17:05:38.337

    0

    R, 43 39 37 bytes

    This is an anonymous function.

    function(n)cat(rbind(1:n,n:1),sep="")
    

    It's 35 bytes if I use pryr::f() like in the other answer:

    pryr::f(cat(rbind(1:n,n:1),sep=""))
    

    but needs to be installed (Enter install.packages("pryr") in the R console).

    shadowtalker

    Posted 2017-05-30T10:32:31.487

    Reputation: 461

    1You could save some bytes by not defining s and just using 1:n directly. – user2390246 – 2017-05-30T19:54:46.790

    1you can also save a couple bytes by removing the curly braces from your first answer – Giuseppe – 2017-05-30T19:58:47.557

    0

    Python 2, 67 bytes

    A simple one, just for the collection :)

    n=input()+1
    i=1
    s=""
    while i<n:
        s+=`i`+`n-i`
        i+=1
    print s
    

    Mikhail V

    Posted 2017-05-30T10:32:31.487

    Reputation: 251

    you can use while i<n:s+=`i`+`n-i`;i+=1 to golf off some bytes – Leaky Nun – 2017-06-10T14:48:03.610

    0

    Hexagony, 15 bytes

    {?\"!\{$.(.@).!
    

    Embiggened:

       { ? \
      " ! \ {
     $ . ( . @
      ) . ! .
       . . .
    

    Try it online!

    Sok

    Posted 2017-05-30T10:32:31.487

    Reputation: 5 592

    0

    LOGO, 48 bytes

    to f :n
    for[i 1 :n][(type :i :n+1-:i)]show "
    end
    

    Define a function f that when invoke with parameter = number n, print the result string.

    user202729

    Posted 2017-05-30T10:32:31.487

    Reputation: 14 620

    0

    braingasm, 9 bytes

    ;[>+:<:-]
    

    Simple: Read a number from stdin to the current cell; While the current cell is not zero, go to next cell (initially 0), increase it, output its value, go back, output that value and decrease it.

    daniero

    Posted 2017-05-30T10:32:31.487

    Reputation: 17 193

    0

    Java 8, 53 52 bytes

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

    Try it online!

    -1 bytes thanks to Sara J!

    Benjamin Urquhart

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 262

    52 bytes – Sara J – 2019-04-02T21:57:30.433

    @SaraJ thanks, I forgot about the for-loop trick – Benjamin Urquhart – 2019-04-02T23:57:47.357

    0

    Kotlin, 44 bytes

    {n->(1..n).joinToString(""){"$it${n-it+1}"}}
    
    {n->                                          // n is Int input
        (1..n)                                    // range from 1 to end
              .joinToString("")                   // join items with no separator
                               {                  // transform by
                                "$it${n-it+1}"    // current number and number from end of range
                                              }}  
    

    Lambda that takes an Int and returns a String.

    Try it online!

    snail_

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 982

    42 (btw it's basically identical to the other kotlin answer) – ASCII-only – 2019-03-15T07:16:45.450

    0

    dc, 17 bytes

    [znddn1-d0<M]dsMx
    

    Try it online!

    Sophia Lechner

    Posted 2017-05-30T10:32:31.487

    Reputation: 1 200

    0

    APL(NARS), 13 chars, 26 bytes

    {∊k,¨⌽k←⍕¨⍳⍵}
    

    How to use & test:

      f←{∊k,¨⌽k←⍕¨⍳⍵}
      f 1
    11
      f 26
    12622532442352262172081991810171116121513141413151216111710189198207216225234243252261
    

    RosLuP

    Posted 2017-05-30T10:32:31.487

    Reputation: 3 036

    0

    Ink, 47 bytes

    =f(n)
    ~temp i=n
    -(l)
    ~i--
    {n-i}{1+i}{i:->l}->->
    

    Try it online!

    Sara J

    Posted 2017-05-30T10:32:31.487

    Reputation: 2 576

    0

    recursive

    Posted 2017-05-30T10:32:31.487

    Reputation: 8 616

    0

    Zsh, 32 bytes

    repeat $1 printf $[++i]$[$1+1-i]
    

    Try it online!

    I like trying to beat Bash+coreutils with pure zsh, but sadly that is not the case here.


    Cooler, but one byte longer (33 bytes):

    a=({$1..1})
    <<<${(j::)${(n)a}:^a}
    

    Try it online!

    GammaFunction

    Posted 2017-05-30T10:32:31.487

    Reputation: 2 838