39
\$\begingroup\$

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.

\$\endgroup\$
0

77 Answers 77

19
\$\begingroup\$

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

\$\endgroup\$
11
\$\begingroup\$

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

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

\$\endgroup\$
4
  • \$\begingroup\$ if that is not acceptable i can change it for seq $1 -1 1|nl|tr -d ' \n\t' 8 bytes more \$\endgroup\$
    – marcosm
    Commented May 30, 2017 at 12:24
  • 1
    \$\begingroup\$ The 20 byte submission is invalid. My upvote is for the 25 byte submission. \$\endgroup\$ Commented May 31, 2017 at 0:03
  • \$\begingroup\$ As Digital Trauma noted, the 20-byte solution is invalid. \$\endgroup\$ Commented May 31, 2017 at 11:49
  • \$\begingroup\$ 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 \$\endgroup\$
    – marcosm
    Commented May 31, 2017 at 14:06
8
\$\begingroup\$

-5 thanks to Ørjan Johansen

Haskell, 33 bytes

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

Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ (1) A do expression is shorter than >>= plus a lambda. (2) However, the shows can be combined by using >>=show. \$\endgroup\$ Commented May 30, 2017 at 12:18
7
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Note that this only works in interactive mode, and requires the user to enter n on the command line (instead of passing via stdin). \$\endgroup\$ Commented May 30, 2017 at 19:54
  • \$\begingroup\$ @ssdecontrol Yes, I think that's usually allowed, but I'm fairly new here, could be wrong. \$\endgroup\$ Commented May 30, 2017 at 20:16
  • \$\begingroup\$ 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/… \$\endgroup\$
    – Giuseppe
    Commented May 30, 2017 at 20:28
6
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ A user by the name of rev suggested LÂ.ιJ. \$\endgroup\$ Commented Mar 6, 2019 at 22:20
  • \$\begingroup\$ @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 :) \$\endgroup\$
    – Emigna
    Commented Mar 7, 2019 at 7:10
  • \$\begingroup\$ Well, I only was the messenger; possible @rev should post their own answer. \$\endgroup\$ Commented Mar 7, 2019 at 7:56
  • \$\begingroup\$ @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. \$\endgroup\$
    – Emigna
    Commented Mar 7, 2019 at 8:10
4
\$\begingroup\$

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).
\$\endgroup\$
4
\$\begingroup\$

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!

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

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

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

\$\endgroup\$
1
  • \$\begingroup\$ this could be much more golfed if you removed all that trailing whitespace :P \$\endgroup\$
    – cat
    Commented Jun 1, 2017 at 13:59
4
\$\begingroup\$

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"

\$\endgroup\$
3
  • 2
    \$\begingroup\$ 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]. \$\endgroup\$
    – nimi
    Commented May 30, 2017 at 14:37
  • 1
    \$\begingroup\$ 1) Your current solution is only 48 bytes. 2) You can drop the n in [1..n]: Try it online! \$\endgroup\$
    – Laikoni
    Commented May 31, 2017 at 19:34
  • \$\begingroup\$ 1) Dang off-by-one errors... 2) Good call! \$\endgroup\$ Commented May 31, 2017 at 19:59
3
\$\begingroup\$

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

Octave, 29 bytes

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

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ My implementation was so, so much longer! Nice! =) \$\endgroup\$ Commented May 30, 2017 at 18:56
3
\$\begingroup\$

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

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

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

Java 61 bytes

(int n)->{for(int i=0;i<n;System.out.print(i+1+""+(n-i++)));}
\$\endgroup\$
6
  • 2
    \$\begingroup\$ Also, welcome to PPCG! :) \$\endgroup\$ Commented May 30, 2017 at 15:39
  • \$\begingroup\$ We allow anonymous functions, so (int n)->{//for loop} should work here. \$\endgroup\$ Commented May 30, 2017 at 15:39
  • \$\begingroup\$ Is that better? \$\endgroup\$
    – cheemcheem
    Commented May 30, 2017 at 15:45
  • 2
    \$\begingroup\$ 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). \$\endgroup\$ Commented May 30, 2017 at 15:48
  • \$\begingroup\$ 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 \$\endgroup\$
    – cheemcheem
    Commented May 30, 2017 at 15:58
3
\$\begingroup\$

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

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

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

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ +1, nice use of pryr \$\endgroup\$ Commented May 30, 2017 at 19:48
  • \$\begingroup\$ @ssdecontrol its pretty much staple replacement of function(x) :) \$\endgroup\$
    – JAD
    Commented May 30, 2017 at 19:57
2
\$\begingroup\$

Brachylog, 10 9 bytes

⟦₁g↔ᶻczcc

Try it online!

Explanation

⟦₁           [1, …, Input]
  g↔ᶻc       [[1, …, Input],[Input, …, 1]]
      z      Zip
       cc    Concatenate twice
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Uhm... for(;$argn;)echo++$i,$argn--; ? \$\endgroup\$
    – Christoph
    Commented May 30, 2017 at 13:13
2
\$\begingroup\$

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

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.

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

K (ngn/k), 16 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ r,'|r: -> +|:\ \$\endgroup\$
    – ngn
    Commented Nov 9, 2018 at 13:47
2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – maxb
    Commented Mar 7, 2019 at 9:53
2
\$\begingroup\$

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

Common Lisp, 63 54 bytes

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

Try it online!

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

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

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
\$\endgroup\$
1
  • \$\begingroup\$ @LuisMendo Ah! I thought there was a function that removed whitespace but couldn't find it. Thanks! \$\endgroup\$
    – Suever
    Commented May 30, 2017 at 13:09

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.