[Question]
  [
# Challenge
Write a program or function that takes in a string `s` and integer `n` as parameters. Your program should print (or return) the string when transformed as follows:
Starting in the top-left and moving down and to the right, write `s` as a wave of height `n`. Then, from top to bottom, combine each row as a string (without spaces).
# Example
Given the string "WATERMELON" and a height of 3:
The wave should look like this:
```
W   R   O
 A E M L N
  T   E
```
Then, combine the rows from top to bottom:
```
WRO
AEMLN
TE
```
So, your program should return the string "WROAEMLNTE"
Likewise, "WATERMELON" with height 4 should produce the following wave:
```
W     E
 A   M L
  T R   O
   E     N
```
Your program should then return the string "WEAMLTROEN"
# Rules
## Input
Input can be taken in any reasonable format. The string can be in any case you prefer. You may assume that `0 < n <= s.length`
## Output
Output should consist only of the transformed string (whether returned or printed to STDOUT), plus any trailing newlines.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! Standard loopholes are not allowed.
# Test Cases
```
Input                        Output
programmingpuzzles, 5 ->     piermnlsomgzgapzru
codegolf, 3           ->     cgoeofdl
elephant, 4           ->     enlatehp
1234567, 3            ->     1524637
qwertyuiop, 1         ->     qwertyuiop
```
  
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
Zv3L)t?yn:)2$S}i
```
[Try it online!](https://tio.run/##y00syfn/P6rM2EezxL4yz0rTSCW4NvP/f1Mu9YKi/PSixNzczLz0gtKqqpzUYnUA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@qzNhHs8S@Ms9K00gluDbzf2yES8h/Uy71gqL89KLE3NzMvPSC0qqqnNRidS5jLvXk/JTU9PycNHUuEy711JzUgozEvBKwjKGRsYmpmbk6lyGXemF5alFJZWlmfoE6AA).
### Explanation
Consider inputs `5`, `'programmingpuzzles'`.
```
Zv     % Input, implicit: number n. Symmetric range
       % STACK: [1 2 3 4 5 4 3 2 1]
3L     % Push [1 -1+1j]. When used as an index, this means 1:end-1
       % STACK: [1 2 3 4 5 4 3 2 1], [1 -1+1j]
)      % Index. Removes last element
       % STACK: [1 2 3 4 5 4 3 2]
t      % Duplicate
       % STACK: [1 2 3 4 5 4 3 2], [1 2 3 4 5 4 3 2]
?      %   If non-empty and non-zero
       %   STACK: [1 2 3 4 5 4 3 2]
  y    %   Implict input: string s. Duplicate from below
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 'programmingpuzzles'
  n    %   Number of elements
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 18
  :    %   Range
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], [1 2 3 ··· 17 18]
  )    %   Index modularly
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2 1 2 3 4 5 4 3 2 1 2]
  2$S  %   Two-input sort: stably sorts first input as given by the second
       %   STACK: 'piermnlsomgzgapzru'
}      % Else. This branch is entered when n=1. The stack contains an empty array
       %   STACK: []
  i    %   Take input
       %   STACK: [], [], 'programmingpuzzles'
       % End, implicit
       % Display stack, implicit. Empty arrays are not displayed
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
δÖK…¢ḣ
```
[Try it online!](https://tio.run/##ASQA2/9odXNr///OtMOWS@KApsKi4bij////NP8iV0FURVJNRUxPTiI "Husk – Try It Online")
Works for `n = 1` as well.
## Explanation
```
δÖK…¢ḣ  Implicit inputs, say n=4 and s="WATERMELON"
     ḣ  Range: [1,2,3,4]
    ¢   Cycle: [1,2,3,4,1,2,3,4,1,2,3,4..
   …    Rangify: [1,2,3,4,3,2,1,2,3,4,3,2..
δÖK     Sort s by this list: "WEAMLTROEN"
        Print implicitly.
```
The higher order function `δ` works like this under the hood.
Suppose you have a higher order function that takes a unary function and a list, and returns a new list.
For example, `Ö` takes a function and sorts a list using it as key.
Then `δÖ` takes a binary function and two lists, zips the lists together, applies `Ö` to sort the pairs using the binary function as key, and finally projects the pairs to the second coordinate.
We use `K` as the key function, which simply returns its first argument and ignores the second.
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
s#n=[c|m<-[0..n],(c,i)<-zip s.cycle$[0..n-1]++[n-2,n-3..1],i==m]
```
[Try it online!](https://tio.run/##LY5LDsIgFAD3nsKgC4gPYq2fjXgCXbmsxBDESoRXLG2MjXev3@VkFjMXna7W@75PI5SFeYY1L6ZCoAJqwLE171wcJmEextvx1/BMTSYF8hkgz4XIFDgpg@odxrZJsqAk1lVZ6xAclrHtOm8TgQUDSkx1smXlzwTyD1pv40VjQ2D@wWyWzxfL1V/e7rZuHq2rIoGMqUHQDmXQcXekB5oAGd@8e/um3uL4/c5@@f4F "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 54, 29, 27 26 bytes
-1 byte thanks to hoosierEE
```
([\:#@[$[:}:|@i:@<:@]) ::[
```
[Try it online!](https://tio.run/##bYzBCoJAFEX3fsWjgkmIQVMLHgnzH1OLSd@oMTriGIHkt08ULly0Pefe8/Da5RwiQIj8Xl5xK@RO4oxv0aC4oLiFgCh9GGw4MJ1zBgeYEbQLAipqC@ylRhpaMrZjoCH5S9OF9oOtBtW2TVf1z2ky5L42W2xhS6qs0esOGepr1Y3rSnxM0ux0Xs/UvSjpd4z9Bw "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
function(s,n)intToUtf8(unlist(split(utf8ToInt(s),-(n:(2.9-n)-1)^2)))
```
[Try it online!](https://tio.run/##Xc5Na4QwEAbg@/4K8WICWvBjd9uCBw85FPwAsexlKYibZANxkmpCqX/eiod2m7nNvDzMO60sX5mFwQgFaA4BCzCdejfsGVmQYjZo1lIYZLdLp95g23EYIXhFydNLBDiK8UeCMV4Z8i9FR9qKlE3thyn2fifPveDSNgWpyrojwWHoDQquEOCDgzIXkaIqu7YhtYP0pPjUj6MAru2ySDr7oXfEO9KCTiPIWY184b1eJuvgQd0oV5Jt5LHljgeuqGI36RAqqb73YDaSeU5JCrI39K4dEidpdjyd3Sc7iY9JdkrPjvj8opP5tkLpDcX4n/jLHtD6Aw "R – Try It Online")
* -10 bytes thanks to @Giuseppe
* -17 bytes because I was silly
* -9 bytes and `n=1` case fixed thanks to @J.Doe
* -3 bytes thanks to @JayCe
[Answer]
# [Python 2](https://docs.python.org/2/), ~~119~~ ~~108~~ ~~98~~ ~~92~~ ~~91~~ ~~97~~ ~~93~~ ~~91~~ 90 bytes
```
lambda s,n:''.join(c*(j%(2*n-2or 1)in(i,2*n-i-2))for i in range(n)for j,c in enumerate(s))
```
[Try it online!](https://tio.run/##dZBLb4MwEITPya9YqaqAyKnANpBUaqUcuOUhoUi99EKJIY7Atgw5lD9PndDW9JG97Wi@2dWo9/YoBe6Lp9e@yuq3QwYNEo@O83CSXLj5zD3du3gm5lhqCDwjcXRZ@Rx7XmE0DlyAzkTJXHEVTii/SEyca6azlrmN5/VKc9FC4Tovq32SbpL1busgkwd382e4jNWn/3vJyJvuVslmvd0nN7x05E1Wm/U@3SWjXKVlqbO65qJU566rWGOY0DKKM12LqpF12ZWZ6vTZsrk8sFJWxfCRnS82LyWTxaGyBKuYOmaiHf76SzBRmZaOyhIBJjSM4t8nvokgxDQi8dQS/ieyWP5syqcLCEgYLwFHk4kPASKAb2Cj0vzI3IgBG5osBy4EjCiQG@yoPN9cvN4DEgIdYBOFzG5CaP8B "Python 2 – Try It Online")
-1 byte, thanks to Jonathan Frech
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Σ²Lû¨¾è¼
```
Inspired by [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/174122/52210).  
-3 bytes thanks to *@Adnan*
[Try it online.](https://tio.run/##AS0A0v8wNWFiMWX//86jwrJMw7vCqMK@w6jCvP//cHJvZ3JhbW1pbmdwdXp6bGVzCjU) (No test suite, because the legacy version of 05AB1E didn't had a reset for the `counter_variable`.)
**Explanation:**
```
Σ           # Sort the (implicit) input-string by:
 ²L         #  Create a list in the range [1, second input-integer]
            #   i.e. 5 → [1,2,3,4,5]
   û        #  Palindromize it
            #   i.e. [1,2,3,4,5] → [1,2,3,4,5,4,3,2,1]
    ¨       #  Remove the last item
            #   i.e. [1,2,3,4,5,4,3,2,1] → [1,2,3,4,5,4,3,2]
     ¾è     #  Index into it (with wraparound) using the counter_variable (default 0)
            #   i.e. counter_variable = 0 → 1
            #   i.e. counter_variable = 13 → 4
       ¼    #  And after every iteration, increase the counter_variable by 1
```
NOTE: The `counter_variable` is used, because in the Python Legacy version of 05AB1E, the `Σ` didn't had an index `N`, which it does have in the new Elixir rewrite version of 05AB1E. So why do I still use the Legacy version? Because in the Elixir rewrite it has a bug and doesn't sort for \$n=1\$, which would all result in an empty list `[]` after the indexing. All other test cases work as intended with `Σ²Lû¨Nè`: [try it online](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9ziyN8Du8@tMLv8Ir/tTr/o6OVwh1DXIN8XX38/ZR0jGN1FFBFTMAiBUX56UWJubmZeekFpVVVOanFSjqmYJnk/JTU9PycNJje1JzUgozEvBKYTkMjYxNTM3OQdCwA), but the test case with \$n=1\$ times out without result, even with `--no-lazy` argument flag: [try it online](https://tio.run/##ASwA0/9vc2FiaWX//86jwrJMw7vCqE7DqP//cXdlcnR5dWlvcAox/y0tbm8tbGF6eQ).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
```
¬üÏu´VÑ aV°ÃÔc q
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rPzPdbRW0SBhVrDD1GMgcQ==&input=IldBVEVSTUVMT04iCjM=)
### Explanation
```
 ¬ üÏ   u´ VÑ  aV° Ã Ô c q
Uq üXY{Yu--V*2 aV++} w c q    Ungolfed
                               Implicit: U = input string, V = size of wave
Uq                             Split U into chars.
   üXY{            }           Group the items in U by the following key function:
       Y                         Take the index of the item.
        u--V*2                   Find its value modulo (V-1) * 2.
               aV++              Take the absolute difference between this and (V-1).
                                 This maps e.g. indices [0,1,2,3,4,5,6,7,...] with V=3 to
                                                        [2,1,0,1,2,1,0,1,...]
                                 The items are then grouped by these values, leading to
                                 [[2,6,...],[1,3,5,7,...],[0,4,...]].
                     w         Reverse the result, giving [[0,4,...],[1,3,5,7,...],[2,6,...]].
                       c       Flatten.
                         q     Join back into a single string.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*6 byter fails for height 1; two bytes used to address it ...maybe a 7 can be found?*
```
ŒḄṖȯ1ṁỤị
```
A dyadic link accepting a positive integer and a list of characters which yields a list of characters.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//xZLhuIThuZbIrzHhuYHhu6Thu4v///81/yJwcm9ncmFtbWluZ3B1enpsZXMi "Jelly – Try It Online")**
### How?
```
ŒḄṖȯ1ṁỤị - Link: positive integer N; list of characters, T
ŒḄ       - bounce (implicit range of) N -> [1,2,3,...,N-1,N,N-1,...,3,2,1]
  Ṗ      - pop off the final entry         [1,2,3,...,N-1,N,N-1,...,3,2]
   ȯ1    - OR one                          if this is [] get 1 instead
     ṁ   - mould like T (trim or repeat to make this list the same length as T)
      Ụ  - grade-up (get indices ordered by value - e.g. [1,2,3,2,1,2] -> [1,5,2,4,6,3])
       ị - index into T
```
[Answer]
# JavaScript (ES6), 75 bytes
*Shorter formula suggested by @MattH (-3 bytes)*
Takes input as `(string)(n)`.
```
s=>n=>--n?[...s].map((c,x)=>o[x=x/n&1?n-x%n:x%n]=[o[x]]+c,o=[])&&o.join``:s
```
[Try it online!](https://tio.run/##Zc7RioMwEAXQ9/2KUliJtEas2kIh9kMk0JDGNCXOZBNtXX/ezT51cQfm5Q6HOw/xFEF644YM8KaWji2BNcCaLINLSykNnPbCESL3U8oabCc25ZAUF8imTzjH5ayNKec7uUfW8jRJkD7QwPV6DotECGgVtahJR7bOo/ai7w1oN86zVWGbkjpNN3m@cUb5HmzAXs9auNmPHyst44MabRdNGc17opYaFXY3uzbKKncXMERTrY0CKwZ1d2tTHMqqPp7@1fyaoj5Ux/K0Jl8v5Yfv0aCLqvijInnflh8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 78 bytes
*Saved 4 bytes thanks to @ETHproductions*
Takes input as `(string)(n)`.
```
s=>n=>--n?[...s].map((c,x)=>o[x=n*n-(x%(n*2)-n)**2]=[o[x]]+c,o=[])&&o.join``:s
```
[Try it online!](https://tio.run/##Zc7fasIwGAXw@z2FCJOk2kj/KQjpHqQUDDGNkfT7sqR1XV@@y64c3bk9/DjnIZ4iSG/ckALe1NLxJfAaeJ2m8NEwxkLLeuEIkYeJ8hqbiUMCKZneCSQ5TYEmSd7yJhZtu5cH5E1LdztkDzRwvV7CIhECWsUsatKRrfOoveh7A9qN82xV2FJSUbo5HjfOKN@DDdjrWQs3@/FtpWX8qNF20RTRvBK11Kiwu9m1UVa5u4AhmnJtFFgxqLtbmywvyup0/jfza7IqL0/FeU0@v5QfvkeDLqrsj4rk1S0/ "JavaScript (Node.js) – Try It Online")
[Answer]
# K ( [Kona](https://github.com/kevinlawler/kona) ), 23 bytes
A translation of the [J answer by Galen](https://codegolf.stackexchange.com/a/174121/18872)
```
{y@<(#y)#-1_(!x),|!x-1}
```
[Answer]
# [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), ~~146~~ ~~159~~ 155 bytes
```
1 INPUT S$,N:DIM C$(N):P=1:D=1:FOR I=1 TO LEN(S$):C$(P)=C$(P)+MID$(S$,I,1)
2 IF N>1 THEN P=P+D
3 IF P=N OR P=1 THEN D=-D
4 NEXT:FOR I=1 TO N:PRINT C$(I);:NEXT
```
Updated to handle n=1
Output:
```
? programmingpuzzles, 5
piermnlsomgzgapzru
? codegolf, 3
cgoeofdl
? elephant, 4
enlatehp
? 1234567, 3
1524637
? WATERMELON, 4
WEAMLTROEN
? qwertyuiop, 1
qwertyuiop
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
```
->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join}
```
[Try it online!](https://tio.run/##ddDJbsIwFIXhfZ7iig6yQY5qZ2CBypOwMcExQZ5qJyoJ8OypaRGhC8726tOVfie8Kkfdw3sNnzCS9cac5mll9TYN1rfoRPg2gCGUvC4Wb4jNDWHnM8UXnB5sYy5j4D3UqMBo5ryVnmvdGOm6YVAizPAKXoCs4TrXCK@NClbLQXI3@C75s1m0ld0JaVV9FdPutpJW2HqnbiKPQijh9ty0T4Qwirdi7x5@UJblRbn8DyZBC5aX2fIGaARf38K3fddY92juYDonSQy4MTFgsfr16Ek1DMcjsI/xBw "Perl 6 – Try It Online")
Takes input as a curried function.
### Explanation:
```
->\n{*.comb.sort({-abs n-1-$++%(2*n-2||1)}).join}
->\n{                                           }  # Take an number
     *.comb        # Turn the string into a list of chars
           .sort({                       })   # And sort them by
                           $++    # The index of the char
                              %(2*n-2||1)  # Moduloed by 2*(n-1) or 1 if n is 0
                       n-1-       # Subtract that from n-1
                   abs            # get the absolute value
                  -               # And negate to reverse the list
                                          .join  # and join the characters
```
The sequence that it is sorted by looks like this (for `n=5`):
```
(-4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1 0 -1 -2 -3 -4 -3 -2 -1)
```
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
4 :'x\:(#x)$}:|i:<:y'::[
```
[Try it online!](https://tio.run/##bc1RC4IwEMDx9z7FUcEKKlJnwVGfpF7EbtOYbk0lG/XZTUNIo4N7@R8/7tpMN8AEHJHBCl4IW2i34YCsPuNiVi/nL3ymeMAHQzw1ywnFiQZmUrJZrgqdSScj42zFYI1tt1raKMvSXJrKOUUFAwFhr2KpSYuLYvCdTsX6QlIrMewCgl5RrqKSEvOrSJFJorwcK94rL/T5LtgPjx/l@QEPd@P@/XW7ky0fVaoH3zr1rwvwmjc "J – Try It Online")
Explicit dyadic verb. Run it like `'codegolf' f 3`.
### How it works
```
4 :'x\:(#x)$}:|i:<:y'::[    x: string, y: height
4 :                         Define a dyadic verb:
               i:<:y        Generate a range of -(y-1) .. y-1
            }:|             Take absolute value and remove last
       (#x)$             1) Repeat to match the string's length
    x\:                     Sort x by the decreasing order of above
                     ::[    If 1) causes `Length Error`, return the input string instead
```
Normally, explicit function takes additional 5 bytes in the form of `n :'...'`. But if error handling is added, the difference goes down to 2 bytes due to the parens and space in `(tacit)<space>::`.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes
```
{⍺[⍋(≢⍺)⍴(¯1↓⊢,1↓⌽)⍳⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbuiH/V2azzqXARkaj7q3aJxaL3ho7bJj7oW6YDpnr1A0c2PerfG1v7/r16eWJJalJuak5@nrpCmYMyFJmDCpV5QlJ9elJibm5mXXlBaVZWTWgySMOVST85PSU3Pz0mDakzNSS3ISMwrgWozNDI2MTUzh0omJiWnpIJVGgIA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Powershell, ~~99~~ 95 bytes
```
param($s,$n)$r=,''*$n
$s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_}
-join$r
```
Test script:
```
$f = {
param($s,$n)$r=,''*$n
$s|% t*y|%{$r[((1..$n+$n..1)*$s.Length|gu)[$i++*($n-gt1)]-1]+=$_}
-join$r
}
@(
    ,("1234567", 3            ,     "1524637")
    ,("qwertyuiop", 1         ,     "qwertyuiop")
    ,("codegolf", 3           ,     "cgoeofdl")
    ,("elephant", 4           ,     "enlatehp")
    ,("programmingpuzzles", 5 ,     "piermnlsomgzgapzru")
) | % {
    $s,$n,$e = $_
    $r = &$f $s $n
    "$($r-eq$e): $r"
}
```
Output:
```
True: 1524637
True: qwertyuiop
True: cgoeofdl
True: enlatehp
True: piermnlsomgzgapzru
```
## Explanation
The script:
* creates an array of rows,
* fills rows with appropriate values,
* and returns the joined rows.
The expression `((1..$n+$n..1)*$s.Length|gu`
generates a sequence like `1,2,3,3,2,1,1,2,3,3,2,1...`
and removes adjacent duplicates. `gu` is alias for [Get-Unique](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Get-Unique).
* For `$n=3` the deduplicated sequence is: `1,2,3,2,1,2,3,2,1...`
* For `$n=1` the deduplicated sequence is: `1`
The expression `$i++*($n-gt1)`
returns an index in the deduplicated sequence. `=$i++` if `$n>1`, otherwise `=0`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~75~~ 65 bytes
```
->s,h{a=['']*h;x=-k=1;s.map{|c|a[x+=k=h-x<2?-1:x<1?1:k]+=c};a*''}
```
[Try it online!](https://tio.run/##dc5Li4MwFIbh/fwKcSO0tRAvLdRmigt3XkCELsRFxsZEjCYTlbG2/e3OoikMhVmf5z18cvy6LhVczM9@Q28I5oZRrKg3QbOBwOu3LRK3e3lH@bSGDaTmdLROJjhMR3ACh6ZYw/LhoZVhPBahVbl@9rMgjYIwifVtSZHsN3ahQajp5zTxgyiMs0D/@Ec6SgZ@FGZpEsRKCsmJRG1bd0SM88xw/yrcZyFqLNuO9bwlM0FilqMqS37BhLPqbUtJOObVhSmFGRYUdcPbDtwxNGAqlAKW7bi7/dsr4FrOzt4r8/2D5XAday5eDDzZn8PyCw "Ruby – Try It Online")
Takes input as an array of chars, returns string
How it wokrs:
* Create `h` strings
* For each character in the input string, decide which string to put it in based on its index (the index of the string to be modified goes up until `h` and then down until `0` and so on)
* Return all the strings joined together
[Answer]
# C, ~~142~~ 134 bytes
*8 bytes saved thanks to Jonathan Frech*
Code:
```
t;i;j;d;f(s,n)char*s;{for(t=strlen(s),i=0;i<n;i++)for(j=0;j+i<t;j=d+i+(n<2))d=j-i+2*~-n,putchar(s[i+j]),i>0&i<n-1&d<t&&putchar(s[d]);}
```
Explanation:
```
// C variable and function declaration magic
t;i;j;d;f(s,n)char*s;{
    // Iterate through each "row" of the string
    for(t=strlen(s),i=0;i<n;i++)
        // Iterate through each element on the row
        // Original index iterator here was j+=2*(n-1), which is a full "zig-zag" forward
        // The (n<2) is for the edge case of n==1, which will break the existing logic.
        for(j=0; j+i<t; j=d+i+(n<2))
            // If j+i is the "zig", d is the "zag": Original index was d=j+i+2*(n-i-1)
            // Two's complement swag here courtesy of Jonathan Frech
            d=j-i+2*~-n,
            putchar(s[i+j]),
            // Short circuit logic to write the "zag" character for the middle rows
            i>0 & i<n-1 & d<t && putchar(s[d]);
}
```
[Try it online!](https://ideone.com/yxer15)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
⭆ＮΦη¬⌊Ｅ²﹪⁺μ⎇νι±ι∨⊗⊖θ¹
```
[Try it online!](https://tio.run/##LYxNC8IwEETv/oocNxAP6tGT0AqCaYsWPKftUgP5qOtG8NfHFJzLPJjHjE9DYzQu545sYLhzqVmbBS5hSdwkPyCBVOJsHRd6KtFEBm2D9cnDKu6V0HFKLkLn0hu8Ej1SMPSFoIQtPs6GEayU5aYlqGIaHE5Q4UjoMXDh17rt5D/HnA@bx6mvb7q@tk3eftwP "Charcoal – Try It Online") Link is to verbose version of code. Works by noting that indices \$ m \$ of the characters on line \$ i \$ satisfy the relation \$ m \pm i = 0 \pmod {2n - 2} \$. Explanation:
```
 Ｎ                      First input as a number
⭆                       Map over implicit range and join
   η                    Second input
  Φ                     Filter over characters
       ²                Literal 2
      Ｅ                 Map over implicit range
          μ             Character index
             ι ι        Outer index
              ±         Negate
            ν           Inner index
           ⎇            Ternary
         ⁺              Plus
                   θ    First input
                  ⊖     Decremented
                 ⊗      Doubled
                    ¹   Literal 1
                ∨       Logical Or
        ﹪               Modulo
     ⌊                  Minimum
    ¬                   Logical Not
                        Implicitly print
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 191 bytes
```
	S =INPUT
	N =INPUT
	A =ARRAY(N)
	A<1> =EQ(N,1) S	:S(O)
I	I =I + -1 ^ D
	S LEN(1) . X REM . S	:F(O)
	A<I> =A<I> X
	D =EQ(I,N) 1
	D =EQ(I * D,1)	:(I)
O	Y =Y + 1
	O =O A<Y>	:S(O)
	OUTPUT =O
END
```
[Try it online!](https://tio.run/##PY7LCsIwEEXXyVfcZaJVKHRVmkIgEQKaaFuh2QgKBRelFfT/41ikm3kezsx7mh/zWKTEWijnz9eOM79WGko3jY7CS2qqvIayF@GzXKJlZSuC5I45wrHFLscNhpPnaL0gYo8ejT1RJvbwY0nhSLHEnjOz2FzmJfK1wwaG/KwUTvLAIlQkOe0DVICuYv0/zMK1oydpyq03KQ3j8Hrepw8vvg "SNOBOL4 (CSNOBOL4) – Try It Online")
Takes `S` then `N` on separate lines.
### Explanation:
```
	S =INPUT			;* read S
	N =INPUT			;* read N
	A =ARRAY(N)			;* create array of size N
	A<1> =EQ(N,1) S	:S(O)		;* if N = 1, set A<1> to S and jump to O
I	I =I + -1 ^ D			;* index into I by I + (-1)^D (D starts as '' == 0)
	S LEN(1) . X REM . S	:F(O)	;* extract the first character as X and set S to the
					;* remaining characters, jumping to O when S is empty
	A<I> =A<I> X			;* set A<I> to A<I> concatenated with X
	D =EQ(I,N) 1			;* if I == N, D=1
	D =EQ(I * D,1)	:(I)		;* if I == D == 1, D = 0. Goto I
O	Y =Y + 1			;* increment the counter
	O =O A<Y>	:S(O)		;* concatenate the array contents until last cell
	OUTPUT =O			;* and print
END
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~105~~ 84 bytes
```
import StdEnv,Data.List
$s n=[c\\l<-[1..n],c<-s&m<-cycle([1..n]++[n-1,n-2..2])|m==l]
```
[Try it online!](https://tio.run/##JcxPC4IwGIDxe59iB8lCN9Cu7hDoIbA/ZNBh7vAyNQbba7gVCH32VuDx@R0eZXrAYMfuZXpiQWPQ9jlOnjS@q/CdluCB1dr5VeQIcqHa1hRUZIyhTFVB3doWVM3K9JsFk0QgzVKkOWO53H4s50aGxsP/yUlERHzf36rrsarPp1iSXfiqwcDDBXqoQzkjWK2WuBjwwzjZHw "Clean – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
c=>g=(s,d=c*2-2,r=d,n=o='')=>s&&([...s].map((c,i)=>i%d%r?n+=c:o+=c),o)+g(n,r-1,r-2)
```
[Try it online!](https://tio.run/##bc5Rb8IgEAfw930KY6LCpJjSVhMT3AdZ9kCAIgY4Bq3L@uU7fHK6XXL38L/8cncRV5FlsnGoAig993yW/GQ4ykRx@coqRhJXJHDgmw3mp7xeo3dKaf6gXkSEJLEltSu1Sm9hy@URysAE8NagQFJVl2Z4lhAyOE0dGNSjDqNlTGCS8N4GE8dpcjovMV7sdotodfLBZfBmMiJOaXx51E3RsvxqwPU3c6@ipQENvXJPpi1GOx3PIgx/jA5ODPoc/7lTs6bt9odHcjN1x9p9c3gidSGfXzoN36OF@FsVcl/MPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~22~~ 21 bytes
```
|seMhD,V*lz+PUQP_UQzz
```
Takes input as `n` followed by `s` on separate lines. Try it online [here](https://pyth.herokuapp.com/?code=%7CseMhD%2CV%2alz%2BPUQP_UQzz&input=3%0AWATERMELON&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=%7CseMhD%2CV%2alz%2BPUQP_UQzz&test_suite=1&test_suite_input=5%0Aprogrammingpuzzles%0A3%0Acodegolf%0A4%0Aelephant%0A3%0A1234567%0A1%0Aqwertyuiop&debug=0&input_size=2).
```
|seMhD,V*lz+PUQP_UQzz   Implicit: Q=eval(input()), z=remaining input
                        
             UQ         Range [0-Q)
            P           All but last from the above
                         e.g. for Q=3, yields [0,1]
               P_UQ     All but last of reversed range
                         e.g. for Q=3, yields [2,1]
           +            Concatenate the previous two results
                          e.g. for Q=3, yields [0,1,2,1]
        *lz              Repeat len(z) times
      ,V           z    Vectorised pair the above with z, truncating longer to length of shorter
                          e.g. for Q=3, z=WATERMELON, yields:
                          [[0,'W'],[1,'A'],[2,'T'],[1,'E'],[0,'R'],[1,'M'],[2,'E'],[1,'L'],[0,'O'],[1,'N']]
    hD                  Sort the above by the first element
                          Note this is a stable sort, so relative ordering between equal keys is preserved
  eM                    Take the last element of each
 s                      Concatenate into string
                          Note that if n=1, the result of the above will be 0 (sum of empty array)
|                   z   If result of above is falsey, yield z instead
```
*Edit: saved a byte by moving the empty check to the end of processing. Previous version:* `seMhD,V*lz|+PUQP_UQ]0z`
[Answer]
# [Red](http://www.red-lang.org), 153 bytes
```
func[s n][i: v: m: 1 b: collect[foreach c s[keep/only reduce[v i c]v: v + m
if all[n > 1(i: i + 1)%(n - 1)= 1][m: -1 * m]]]foreach k sort b[prin last k]]
```
[Try it online!](https://tio.run/##VYzNSgMxFIX38xSHgUJVisS2CoH6EG5DFmnmZhomfyaZkfblx7jQ4upyvnPul2lYP2gQsjN8NXPQoiBIYTkWDs/BcObQ0TnSVZiYSekLNIqYiNJzDO6KTMOsSSyw0LJ9LXiC76yBck4EvINtm842yh4224BduycwKZp@x/AIL6X8VU8oMVecRco2wKlSMUm5/qQKgz7lOGblvQ1jmm83R6XHsfurdRxojM702N8hOUoXFWqPwx2yl/3h@Pr2b/j5RbleZxtTD9at3w "Red – Try It Online")
## Explanation:
```
f: func [ s n ] [                      ; s is the string, n is the height
    i: 1                               ; index of the current character in the string
    v: 1                               ; value of the "ladder"
    m: 1                               ; step (1 or -1)
    b: collect [                       ; collect the values in a block b
        foreach c s [                  ; foreach character in the string 
            keep/only reduce [ v i c ] ; keep a block of the evaluated [value index char] 
            i: i + 1                   ; increase the index
            v: v + m                   ; calculate the value 
            if all [ n > 1             ; if height is greater than 1 and
                    i % (n - 1) = 1    ; we are at a pick/bottom of the ladder
                   ]
                [ m: -1 * m ]          ; reverse the step
        ]
    ]
    foreach k sort b [ prin last k ]   ; print the characters in the sorted block of blocks
]
```
[Answer]
I have two solutions to the problem. The first solution I did first then I thought of another way to do it that I thought would save bytes but it didn't so I included it anyway.
---
# Solution 1
## [PHP](https://php.net/), ~~152~~ ~~144~~ 116 bytes
```
<?php
for($i=0;$i<$n=$argv[2];$i++)
    for($j=$i;$s=$argv[1][$j];$j+=$n<2|(($f=!$f|!$i)?$i<$n-1?$n+~$i:$i:$i)*2)
        echo $s;
```
* 8 bytes thanks to @JoKing
* 28 bytes thanks to @Shaggy
[Try it online!](https://tio.run/##LcxLCsMgAIThqyQwC60UGqGbqniQkEUo8UWjorSLEHp1G0JhNj8fTHa5Namzy51JhcCrm4CXiApzsZ@RT0cyRk8MCl6g/mmYRoSDA1OIku@EwKgeZu/hqT5ProNGZF/4xzl64XR5utShitZaLsmWeV19tPm9ba@ltvsP "PHP – Try It Online")
---
# Solution 2
## [PHP](https://php.net/), 162 bytes
```
<?php
$s=$argv[0];
$n=$argv[1];
$l=strlen($s);
for($i=0;$i<$l;){
    for($j=0;$j<$n&&$i<$l;)
        $a[$j++].=$s[$i++];
    for($j=$n-2;$j>0&&$i<$l;)
        $a[$j--].=$s[$i++];
}
echo join($a);
```
[Try it online!](https://tio.run/##VY1BC8IgAEb/yg4fY2MYa9DJuX6I7CCxnOJUtDos@u1m4aFuj8eD51ef0nj2q68QGUSQD36cKWzhIbNh8RbMYhvEll5daKBYT6FGGNo@v0J/hB5h67p4CA7ddfOBIXKoTLSUsGTI8dT/t4T8tq/lsrpKO5WvoqUpJR@cDGLblJX@vu9mien0Bg "PHP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 84 bytes
```
->s,n{r=['']*n;[*0...n,*(2-n)..-1].map{|x|r[x.abs]+=s.slice!(0)||''}while s[0];r*''}
```
[Try it online!](https://tio.run/##ZY7NaoNAFEb3PoVZjVq9aNS0RQx0kV2SQih0MczCmPEHxnGYidSoeXZrSa2LLu8558Inm/NtzOLR2Sqb9zLGCBGLR9hyAYDblrF2uAngeASqRPRDO0jcQnJW5ClWoFiZ0pXhmsOA0P2rKBnVFXZJJK3pHg0PIDDnR9FclZ5h9Pn2sTsddvv3I7L1lty1H6HNVsg6l0lVlTwXTdcxqqYqJH8@rS80r1k2UX@hlFFRJPw60WCh3toPws3zkmqGDxD@W@T@hi@vj0XjNw "Ruby – Try It Online")
]