title: String analyser

text:
# Question
Title: String analyser
Use any programming language to display "AWSALILAND" in such a way, so that each letter is in a new line and repeated as many times as its position in the English alphabet. For example letter, (A) should be displayed just once because it is the first letter of the alphabet. Letter D should be displayed 4 times because it is the 4th letter of the alphabet.

So, the output should be this:

```
A
WWWWWWWWWWWWWWWWWWWWWWW
SSSSSSSSSSSSSSSSSSS
A
LLLLLLLLLLLL
IIIIIIIII
LLLLLLLLLLLL
A
NNNNNNNNNNNNNN
DDDD

```

# Answer
> 7 votes
# C# (Visual C# Interactive Compiler), ~~61~~ 59 bytes

```
foreach(var s in"AWSALILAND")WriteLine(new string(s,s-64));

```

Try it online!

@Kevin Cruijssen Thanks, 2 bytes saved by removing { }

# Answer
> 6 votes
# Japt, ~~18~~ 17 bytes

*-1 byte from @Shaggy*

```
`awÑ¢Ó€`u ¬®pIaZc

```

---

```
`awÑ¢Ó€`u ¬®pIaZc   Full program
`awÑ¢Ó€`            Compressed "awasiland"
        u           uppercase
          ¬®        split and map each letter
            p         repeat the letter this many times:
              a         absolute difference of
               Zc         get charcode
             I            and 64

```

Try it online!

# Answer
> 4 votes
# Pyth, 20 bytes

```
jm*d-Cd64"AWSALILAND

```

Try it online here.

```
jm*d-Cd64"AWSALILAND
         "AWSALILAND   String literal "AWSALILAND"
 m                     Map each character of the above, as d, using:
     Cd                  Get character code of d
    -  64                Subtract 64
  *d                     Repeat d that many times
j                      Join on newlines, implicit print

```

**19 byte** alternative, which outputs lower case: `jm*dhxGd"awsaliland` \- link

# Answer
> 4 votes
# PowerShell, 34 bytes

```
"AWSALILAND"|% t*y|%{"$_"*($_-64)}

```

Try it online!

Takes the string `t`oCharArra`y`, then multiplies each letter out the corresponding number of times. Implicit `Write-Output` gives us newlines for free.

Ho-hum.

# Answer
> 4 votes
# brainfuck, 112 bytes

```
+++++++[->++>>++>+>++>>+++>+++[<<<]<<]++++>>+>-->++>-->+>-->++>+[[->+>+<<]----[>+<----]>+>[-<.>]++++++++++.<,<<]

```

Try it online!

The actual word generation can probably be optimised further.

# Answer
> 3 votes
# Scala (51 bytes):

```
"AWSALILAND"map(c=>s"$c"*(c-64)mkString)map println

```

# Scala (41 bytes):

```
for(c<-"AWSALILAND")println(s"$c"*(c-64))

```

Try it online

# Answer
> 3 votes
# Python 3,41 bytes

```
for i in'AWSALILAND':print(i*(ord(i)-64))

```

# Python 2,40 bytes

```
for i in'AWSALILAND':print i*(ord(i)-64)

```

# Answer
> 3 votes
# 05AB1E, 17 bytes

```
.•DθîRI§•ʒAyk>×u,

```

Try it online!

**Explanation**

```
.•DθîRI§•           # push compressed string "awsaliland"
         ʒ          # filter
          Ayk       # get the index of the current letter in the alphabet
             >      # increment
              ×     # repeat it that many times
               u    # upper-case
                ,   # print

```

We only use filter here to save a byte over other loops due to ac implicit copy of the element on the stack. Filter works here since we print in the loop and don't care about the result of the filter.

# Answer
> 3 votes
# Stax,  ~~16~~  15 bytes

```
êôM▄╬æ♠ª+ç█○==.

```

Run and debug it

**Explanation**

```
`'YHu~{YX#`m64-_]*      #Full program, unpacked,
`'YHu~{YX#`             #Compressed "AWSALILAND"
           m            #Use the rest of the program as the block. Print each mapped element with a new-line.
            64          #Put 64 on stack
              -         #Subtract current element by 64
               _        #Get current index
                ]       #Make a 1 element array
                 *      #Duplicate that many times

```

Saved one byte by figuring out that the "\*" command works with \[arr int\] and \[int arr\].

# Answer
> 3 votes
# Charcoal, 17 bytes

```
ＥAWSALILAND×ι⊕⌕αι

```

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

```
 AWSALILAND         Literal string
Ｅ                   Map over characters
                ι   Current character
               α    Uppercase alphabet
              ⌕     Find
             ⊕      Increment
            ι       Current character
           ×        Repeat
                    Implicitly print each entry on its own line

```

# Answer
> 3 votes
# , ~~64~~ 61 bytes

R's clunky string handling characteristics on full display...

-3 thanks to @Giuseppe, who noticed it's actually shorter to *convert a string from utf8 to int and back again* than using R's native string splitting function...

```
write(strrep(intToUtf8(s<-utf8ToInt("AWSALILAND"),T),s-64),1)

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Classic), 22 bytes

A more elegant, tacit solution thanks to Adám!

```
(↑⎕A∘⍳⍴¨⊢)'AWSALILAND'

```

Try it online!

Initial solution:

```
↑a⍴¨⍨⎕A⍳a←'AWSALILAND'

```

Try it online!

# Answer
> 2 votes
# Java 11, ~~89~~ ~~83~~ ~~82~~ 81 bytes

```
v->"AWSALILAND".chars().forEach(c->System.out.println(((char)c+"").repeat(c-64)))

```

-1 byte thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
v->                      // Method with empty unused parameter and no return-type
  "AWSALILAND".chars().forEach(c->
                         //  Loop over the characters as integer unicode values
    System.out.println(  //   Print with trailing newline:
      ((char)c+"")       //    The current character converted to char and then String
       .repeat(c-64)))   //    repeated the unicode value minus 64 amount of times

```

# Answer
> 2 votes
# Perl 5, 35 bytes

```
say$_ x(31&ord)for AWSALILAND=~/./g

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 23 22 bytes

```
(32!r)#'r:"AWSALILAND"

```

Try it online!

```
         r:"AWSALILAND"  // set variable r to the string
(32!r)                   // mod 32 each string in r, the operation will use ASCII number
       #'                // for each value in the array, take that amount of the corresponding character in the string

```

# Answer
> 1 votes
# , 31 bytes

```
echo(#&>~_64+a.i.])'AWSALILAND'

```

Try it online!

## Explanation:

```
echo(#&>~_64+a.i.])'AWSALILAND' - print
     #  ~                       - copy (arguments reversed)
      &>                        - each character (can be "0)
               i.               - the index of
                 ]              - the characters in
             a.                 - the alphabet
         _64+                   - minus 64 (times)

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 88 bytes

```
	S ='AWSALILAND'
L	S LEN(1) . X REM . S :F(END)
	&UCASE X @Y
	OUTPUT =DUPL(X,Y)	:(L)
END

```

Try it online!

# Answer
> 1 votes
# MATL, 20 bytes

```
'AWSALILAND'"@@64-Y"

```

Try it online!

### Explanation

```
'AWSALILAND'   % Push this string
"              % For each character in this string
  @            %   Push current character
  @            %   Push current character
  64-          %   Implicitly convert to codepoint and subtract 64
  Y"           %   Repeat that many times. Gives a string with the repeated character
               % Implicit end
               % Implicit display

```

# Answer
> 1 votes
# Red, 59 bytes

```
foreach c"AWSALILAND"[print pad/with c to-integer c - 64 c]

```

Try it online!

# Answer
> 1 votes
# Z80Golf, 30 bytes

```
00000000: 2114 007e d640 477e ff10 fd23 3e0a ff7e  !..~.@G~...#>..~
00000010: b720 f076 4157 5341 4c49 4c41 4e44       . .vAWSALILAND

```

Try it online!

Assembly:

```
ld hl,str			;load address of str
start:
	ld a,(hl)		;get current char
	sub 64 		;get letter num in alphabet
	ld b,a			;store in b
	ld a,(hl)		;get current char
	print_char:
		rst 38h 	;print letter
		djnz print_char	;repeat print loop b times
	inc hl			;increment index of str, to get next char
	ld a,10
	rst 38h 		;print newline
	ld a,(hl)		;get current char
	or a
	jr nz, start		;if current char!=0, keep looping
end:
	halt			;end program (if current char==0)
str:
	db 'AWSALILAND'

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~65~~ 63 bytes

```
i=>[...'AWSALILAND'].map(c=>c.repeat(parseInt(c,36)-9)).join`
`

```

Try it online!

**Explanation:**

```
i=>                         // Prints the result of this function
  [...'AWSALILAND'].map(c=> // Loop over the characters
    c.repeat(               // Repeat the current character
      parseInt(c,36)-9)))   // Character to alphabetical position
        .join`
        `                   // Prints a newline after every new char

```

**Edit:** -2 bytes thanks to @BrianH.

# Answer
> 1 votes
## Haskell, 43 bytes

```
mapM(putStrLn. \c->c<$['A'..c])"AWSALILAND"

```

Try it online!

# Answer
> 1 votes
# SOGL V0.12, 16 bytes

```
i|╚┌ž′ø¹‘U{Z⁴W*P

```

Try it Here!

# Answer
> 1 votes
# T-SQL, 83 bytes

```
SELECT REPLICATE(value,ASCII(value)-64)FROM STRING_SPLIT('A-W-S-A-L-I-L-A-N-D','-')

```

`STRING_SPLIT` is supported by SQL 2016 and later.

# Answer
> 1 votes
# Pip `-l`, 21 bytes

```
_X A_-64M"AWSALILAND"

```

Try it online!

```
         "AWSALILAND"  Literal string
        M              to the characters of which we map this function:
   A_                   ASCII value of character
     -64                minus 64 (= 1-based index in alphabet)
_X                      String-repeat character that many times
                       Autoprint, with each item on its own line (-l flag)

```

# Answer
> 1 votes
# C (clang), ~~96~~ ~~95~~ ~~77~~ 73 bytes

```
*s=L" AWSALILAND";main(i){for(;*++s;puts(""))for(i=*s-63;--i;printf(s));}

```

Try it online!

-18 bytes thanks to @ErikF

-5 bytes thanks to @ceilingcat

# Answer
> 1 votes
# Julia, 41 bytes

```
[println(l^(l-'@')) for l∈"AWSALILAND"]

```

Try it online!

# Answer
> 1 votes
# Swift, 95 bytes

```
"AWSALILAND".unicodeScalars.forEach{print(String(repeating:String($0),count:Int($0.value)-64))}

```

**Try it online!**

**How?**

```
"AWSALILAND"                             // Starting string
    .unicodeScalars                      // Convert into a list of unicode values
    .forEach {                           // Loop over each number
        print(String(                    // Create a string
            repeating: String($0),       //   that repeats each character
            count: Int($0.value) - 64))  //   the unicode value minus 64 (the offset)
}

```

# Answer
> 1 votes
# \>\<\>, 40 bytes

```
"DNALILASWA"v
 oa~~<v-*88:<
-:0=?^>$:o$1

```

Try it online!

# Answer
> 1 votes
# JavaScript, ~~74~~ 68 bytes

```
for(i in s="AWSALILAND")console.log(s[i].repeat(s.charCodeAt(i)-64))

```
* 74-\>68, -6B for changing `for` loop to `for...in`, saving bytes on loop statement, removed increment, and removing statement to save the character.

# Answer
> 1 votes
# Vyxal `j`, ~~18~~ 16 bytes

```
`AWSALILAND`ƛøA*

```

Try it Online!

### Explained

```
`AWSALILAND`ƛøA*
            ƛ    # mapping lambda
             øA  # string to number in alphabet
               * # times the character

```

`j` flag to print with newlines

# Answer
> 0 votes
# Jelly, 20 bytes

```
“AWSALILAND”ẋ"O_64ƊY

```

Try it online!

# Answer
> 0 votes
# MBASIC, 86 bytes

```
 1 S$="AWSALILAND":FOR I=1 TO LEN(S$):P$=MID$(S$,I,1):PRINT STRING$(ASC(P$)-64,P$):NEXT

```

Output:

```
A
WWWWWWWWWWWWWWWWWWWWWWW
SSSSSSSSSSSSSSSSSSS
A
LLLLLLLLLLLL
IIIIIIIII
LLLLLLLLLLLL
A
NNNNNNNNNNNNNN
DDDD

```

# Answer
> 0 votes
# PHP, 93 bytes

```
<?=!array_walk(str_split("AWSALILAND",1),function(&$v){echo str_repeat($v,ord($v)-64)."
";});

```

Try it online!

---

# PHP, 81 bytes

```
<?php for(;$i++<10;)echo str_repeat(($s=AWSALILAND)[$i-1],ord($s[$i-1])-64)."
";

```

Try it online!

# Answer
> 0 votes
# Dart, 83 bytes

```
'AWSALILAND'.runes.forEach((r)=>print(String.fromCharCodes(List.filled(r-64, r))));

```

Try it online!

# Answer
> 0 votes
# PHP, 71 bytes

```
<? for($i=0;$c="AWSALILAND"[$i++];)echo str_repeat($c,ord($c)-64)."\n";

```

Try it online!

# Answer
> 0 votes
# Common Lisp, 96 bytes

```
(defun x(s)(dotimes(i(length s))(dotimes(j(-(char-int(char s i))96))(princ(char s i)))(terpri)))

```

Try it online!

# Answer
> 0 votes
# Jelly, 17 bytes

```
“þ⁷ʂ:ñ⁵1»O_96×ŒuY

```

**Try it online!**

### How?

```
“þ⁷ʂ:ñ⁵1»O_96×ŒuY - Main Link: no arguments
“þ⁷ʂ:ñ⁵1»         - compressed list of characters (using words aws, ali & land = awsaliland)
         O        - cast to ordinals = [97,119,115,97,108,105,108,97,110,100]
          _96     - subtract 96 = [1,23,19,1,12,9,12,1,14,4]
              Œu  - upper-case the chain's argument = "AWSALILAND"
             ×    - multiply = ["A","W...W","S...S","A","L...L","I...I","L...L","A","N...N","DDDD"]
                Y - join with newline characters = ["A",'\n',"W...W",'\n',"S...S",'\n',"A",'\n',"L...L",'\n',"I...I",'\n',"L...L",'\n',"A",'\n',"N...N",'\n',"DDDD"]
                  - implicit (smashing) print

```

---

Also @ 17 bytes: `“þ⁷ʂ:ñ⁵1»ØaiⱮ×ŒuY`, and `“þ⁷ʂ:ñ⁵1»O%32×ŒuY`

# Answer
> 0 votes
# C++ (gcc), 90 83 bytes

```
#include<map>
int main(){for(auto c:"AWSALILAND")c&&puts(&std::string(c-64,c)[0]);}

```

Try it online!

Thanks to movatica for shaving off 7 bytes!

# Answer
> 0 votes
# Go, 100 bytes

```
import(."fmt"
."strings")
func a(){for _,c:=range"AWSALILAND"{Println(Repeat(string(c),int(c)-64))}}

```

Try it online!

# Answer
> 0 votes
# QBasic, 57 bytes

```
FOR i=1TO 10
c=ASC("AWSALILAND",i)
?STRING$(c-64,c)
NEXT

```

I'm so glad I was able to avoid using `MID$()` for this challenge!

### How it works

* Run a `FOR` loop over (1-based) indices of the characters in the string
* Store the ASCII code of the current character as `c`
* Create a string of `c-64` repetitions of character `c` and print it

# Answer
> 0 votes
# PHP, 58 bytes

```
while($c=AWSALILAND[$i++])echo str_pad("
",ord($c)-63,$c);

```

prints a leading linebreak. Run with `-nr` or try it online.

# Answer
> 0 votes
# Python 2, 38 bytes

```
for c in'AWSALILAND':print ord(c)%64*c

```

Try it online!

# Answer
> 0 votes
# Bubblegum, 29 bytes

```
00000000: 73e4 0ac7 0eb8 8231 0197 2397 0f12 e0f2  s......1..#.....
00000010: 8401 1461 a02a 3f14 c0e5 0204 00         ...a.*?......

```

Try it online!

*I'm sorry...*

# Answer
> 0 votes
# F# (.NET Core), 66 bytes

```
"AWSALILAND"|>Seq.iter(fun x->printfn"%s"(new string(x,int x-64)))

```

Try it online!

Same logic than @pocki\_c's answer

I am not used to F# golfing. All inputs are welcome :)

# Answer
> 0 votes
# Ruby, 39 bytes

```
"AWSALILAND".chars{|x|x.*x.ord-64}

```

Try it offline!

# Answer
> 0 votes
# Java (JDK), 162 bytes

```
static void m(){String n="AWSALILAND";for(int i=0;i<n.length();i++){char c=n.charAt(i);int v=c;for(int z=0;z<v-64;z++)System.out.print(c);System.out.println("");}

```

Try it online!

# Answer
> 0 votes
# APL(NARS), 22 chars, 44 bytes

```
⊃a/¨⍨⎕A⍳a←'AWSALILAND'

```

test

```
A
WWWWWWWWWWWWWWWWWWWWWWW
SSSSSSSSSSSSSSSSSSS
A
LLLLLLLLLLLL
IIIIIIIII
LLLLLLLLLLLL
A
NNNNNNNNNNNNNN
DDDD

```

# Answer
> 0 votes
# ///, 82 bytes

```
/$/NN//#/SSS//"/WWW//!/LLLL/A
"""""""WW
######S
A
!!!
IIIIIIIII
!!!
A
$$$$$$$
DDDD

```

Try it online!

# Answer
> 0 votes
## Turing Machine But Way Worse \- 4349 bytes

```
0 0 0 1 1 0 0
0 1 1 1 2 0 0
0 2 0 1 3 0 0
0 3 0 1 4 0 0
0 4 0 1 5 0 0
0 5 0 1 6 0 0
0 6 0 1 7 0 0
0 7 1 0 8 1 0
0 8 1 1 0 0 0
1 0 0 0 1 0 0
1 1 1 0 9 0 0
0 9 0 0 10 0 0
0 10 1 0 11 0 0
0 11 0 0 12 0 0
0 12 0 0 2 0 0
1 2 0 0 13 1 0
0 13 0 1 14 0 0
0 14 1 0 15 0 0
0 15 0 1 3 0 0
1 3 1 1 16 0 0
0 16 0 1 17 0 0
0 17 1 0 18 0 0
0 18 0 1 4 0 0
1 4 1 1 5 0 0
1 5 0 0 6 0 0
1 6 1 1 19 0 0
0 19 0 1 20 0 0
0 20 1 1 7 0 0
1 7 1 1 21 0 0
0 21 1 0 8 1 0
1 8 1 0 9 1 0
1 9 1 0 22 1 0
0 22 0 0 10 1 0
1 10 1 1 23 1 0
0 23 0 0 11 1 0
1 11 1 1 24 1 0
0 24 0 0 12 1 0
1 12 1 1 25 1 0
0 25 0 0 13 1 0
1 13 1 1 26 1 0
0 26 0 0 14 1 0
1 14 1 1 27 1 0
0 27 0 0 15 1 0
1 15 1 1 28 1 0
0 28 0 0 16 1 0
1 16 1 1 29 1 0
0 29 0 0 17 1 0
1 17 1 1 30 1 0
0 30 0 0 18 1 0
1 18 1 1 31 1 0
0 31 0 0 19 1 0
1 19 1 1 32 1 0
0 32 1 1 20 0 0
1 20 0 1 21 0 0
1 21 1 1 22 0 0
1 22 0 0 23 0 0
1 23 1 0 33 0 0
0 33 0 0 24 0 0
1 24 1 0 25 0 0
1 25 0 0 34 0 0
0 34 0 0 26 0 0
1 26 0 0 35 1 0
0 35 0 1 36 0 0
0 36 1 0 37 0 0
0 37 0 1 27 0 0
1 27 1 1 38 0 0
0 38 0 1 39 0 0
0 39 1 0 40 0 0
0 40 0 1 28 0 0
1 28 1 1 29 0 0
1 29 0 1 41 0 0
0 41 0 1 30 0 0
1 30 1 1 42 0 0
0 42 1 0 31 1 0
1 31 1 0 43 1 0
0 43 0 0 44 1 0
0 44 0 0 32 1 0
1 32 1 1 45 1 0
0 45 0 0 33 1 0
1 33 1 1 46 1 0
0 46 0 0 34 1 0
1 34 1 1 47 1 0
0 47 0 0 35 1 0
1 35 1 1 48 1 0
0 48 0 0 36 1 0
1 36 1 1 49 1 0
0 49 0 0 37 1 0
1 37 1 1 50 1 0
0 50 0 0 38 1 0
1 38 1 1 51 1 0
0 51 0 0 39 1 0
1 39 1 1 52 1 0
0 52 1 1 53 0 0
0 53 0 1 40 0 0
1 40 1 1 41 0 0
1 41 0 0 42 0 0
1 42 1 0 54 0 0
0 54 0 0 43 0 0
1 43 1 0 44 0 0
1 44 0 0 55 0 0
0 55 0 0 45 0 0
1 45 0 0 56 1 0
0 56 0 1 57 0 0
0 57 1 0 58 0 0
0 58 0 1 46 0 0
1 46 1 1 59 0 0
0 59 0 1 60 0 0
0 60 0 1 47 0 0
1 47 0 0 61 0 0
0 61 0 1 62 0 0
0 62 0 1 63 0 0
0 63 0 1 48 0 0
1 48 0 1 64 0 0
0 64 1 0 65 1 0
0 65 1 1 49 0 0
1 49 0 0 50 0 0
1 50 1 0 66 0 0
0 66 0 0 67 0 0
0 67 1 0 68 0 0
0 68 0 0 69 0 0
0 69 0 0 51 0 0
1 51 0 0 70 1 0
0 70 0 1 71 0 0
0 71 1 0 72 0 0
0 72 0 1 52 0 0
1 52 1 1 73 0 0
0 73 0 1 74 0 0
0 74 0 1 53 0 0
1 53 1 1 75 0 0
0 75 1 1 54 0 0
1 54 0 0 55 1 0
1 55 1 0 56 1 0
1 56 1 0 76 1 0
0 76 0 1 57 1 0
1 57 1 0 77 1 0
0 77 0 1 58 1 0
1 58 1 0 78 1 0
0 78 0 1 59 1 0
1 59 1 0 79 1 0
0 79 0 1 60 1 0
1 60 1 0 80 1 0
0 80 0 1 61 1 0
1 61 1 1 62 0 0
1 62 0 1 81 0 0
0 81 1 0 82 0 0
0 82 0 0 63 0 0
1 63 1 0 83 0 0
0 83 0 0 84 0 0
0 84 0 0 64 0 0
1 64 0 0 85 1 0
0 85 0 1 86 0 0
0 86 1 0 87 0 0
0 87 0 1 65 0 0
1 65 1 1 88 0 0
0 88 0 1 89 0 0
0 89 0 1 66 0 0
1 66 1 1 90 0 0
0 90 0 1 67 0 0
1 67 0 1 91 0 0
0 91 1 0 92 1 0
0 92 0 0 93 1 0
0 93 0 0 68 1 0
1 68 1 0 94 1 0
0 94 0 1 69 1 0
1 69 1 0 95 1 0
0 95 0 1 70 1 0
1 70 1 0 96 1 0
0 96 0 1 71 1 0
1 71 1 1 97 0 0
0 97 0 1 98 0 0
0 98 1 1 72 0 0
1 72 0 0 73 0 0
1 73 1 0 99 0 0
0 99 0 0 74 0 0
1 74 1 0 100 0 0
0 100 0 0 101 0 0
0 101 0 0 75 0 0
1 75 0 0 102 1 0
0 102 0 1 103 0 0
0 103 1 0 104 0 0
0 104 0 1 76 0 0
1 76 1 1 105 0 0
0 105 0 1 106 0 0
0 106 0 1 77 0 0
1 77 1 1 107 0 0
0 107 1 1 78 0 0
1 78 0 0 79 1 0
1 79 1 0 80 1 0
1 80 1 0 108 1 0
0 108 0 1 81 1 0
1 81 1 0 109 1 0
0 109 0 1 82 1 0
1 82 1 0 110 1 0
0 110 0 1 83 1 0
1 83 1 0 111 1 0
0 111 0 1 84 1 0
1 84 1 0 112 1 0
0 112 0 1 85 1 0
1 85 1 1 86 0 0
1 86 0 1 113 0 0
0 113 1 0 114 0 0
0 114 0 0 87 0 0
1 87 1 0 115 0 0
0 115 0 0 116 0 0
0 116 0 0 88 0 0
1 88 0 0 117 1 0
0 117 0 1 118 0 0
0 118 1 0 119 0 0
0 119 0 1 89 0 0
1 89 1 1 120 0 0
0 120 0 1 121 0 0
0 121 0 1 90 0 0
1 90 0 0 122 0 0
0 122 0 1 123 0 0
0 123 0 1 124 0 0
0 124 0 1 91 0 0
1 91 0 1 125 0 0
0 125 1 0 126 1 0
0 126 1 1 92 0 0
1 92 0 0 93 0 0
1 93 1 0 127 0 0
0 127 0 0 128 0 0
0 128 1 0 129 0 0
0 129 0 0 130 0 0
0 130 0 0 94 0 0
1 94 0 0 131 1 0
0 131 0 1 132 0 0
0 132 1 1 133 0 0
0 133 0 1 134 0 0
0 134 0 1 95 0 0
1 95 1 1 135 0 0
0 135 1 0 96 1 0
1 96 1 0 136 1 0
0 136 0 1 97 1 0
1 97 1 0 137 1 0
0 137 0 1 98 1 0
1 98 1 0 138 1 0
0 138 0 1 99 1 0
1 99 1 0 139 1 0
0 139 0 1 100 1 0
1 100 1 0 140 1 0
0 140 0 1 101 1 0
1 101 1 0 141 1 0
0 141 0 1 102 1 0
1 102 1 0 142 1 0
0 142 0 1 103 0 0
1 103 1 1 104 0 0
1 104 0 0 105 0 0
1 105 1 0 143 0 0
0 143 0 0 144 0 0
0 144 0 0 106 0 0
1 106 0 0 145 1 0
0 145 0 1 146 0 0
0 146 1 0 147 0 0
0 147 0 1 107 0 0
1 107 1 1 148 0 0
0 148 0 1 149 0 0
0 149 0 1 108 0 0
1 108 0 0 150 0 0
0 150 0 1 151 0 0
0 151 0 1 152 0 0
0 152 1 1 109 0 0
1 109 0 0 110 1 0
1 110 1 0 153 1 0
0 153 0 0 154 1 0
0 154 0 1 155 1 1

```

Made with the help of ASCII\_only's program generator

# Answer
> 0 votes
# Tcl, 88 bytes

```
lmap x [split AWSALILAND ""] {set s ""
time {set s $s$x} [expr [scan $x %c]-64]
puts $s}

```

Try it online!

# Answer
> 0 votes
# Perl 6, 37 bytes

```
say .chr x$_-64 for "AWSALILAND".ords

```

Try it online!

# Answer
> 0 votes
# VBA (Excel), 70 bytes

using Immediate window

```
a="AWSALILAND":For x=1To Len(a):b=Mid(a,x,1):?String(Asc(b)-64,b):Next

```

# Answer
> 0 votes
# 8088 machine code, IBM PC DOS, 40 bytes

**Listing:**

```
B4 02       MOV  AH, 2          ; DOS API display char function
B1 0A       MOV  CL, 10         ; CL length of string
BE 011E     MOV  SI, OFFSET S   ; point SI to AWSALILAND string
    LOOP_CHAR:
AC          LODSB               ; load next byte into AL
8A D0       MOV  DL, AL         ; put in DL for display
2C 40       SUB  AL, 'A'-1      ; convert ASCII char to 1-based counter
8A D8       MOV  BL, AL         ; move to BL for repeat loop
    LOOP_REP:
CD 21       INT  21H            ; display char in DL
4B          DEC  BX             ; decrement repeat counter
75 FB       JNZ  LOOP_REP       ; repeat char loop
B2 0D       MOV  DL, 0DH        ; display CR
CD 21       INT  21H
B2 0A       MOV  DL, 0AH        ; display LF
CD 21       INT  21H
E2 EA       LOOP LOOP_CHAR      ; next char loop
C3          RET                 ; return to DOS

S   DB      'AWSALILAND'        ; define static string in memory

```

Actually turned out to be longer than I thought. Of course, it doesn't help that it costs 8 bytes to display a newline using the DOS console API.

**Output**

Download and test AWA.COM.

# Answer
> 0 votes
# Deadfish~, 192 bytes

```
{i}ddsic{{d}}{i}cs{d}dddccc{cc}{{d}}{i}cdsii{c}ccccccccc{{d}}{i}cddsic{{d}}{i}cdsddddd{c}cc{{d}}{i}cdds{i}dccccccccc{{d}}{i}cdsddddd{c}cc{{d}}{i}cddsic{{d}}{i}cdsddd{c}cccc{{d}}{i}cddsiiiicccc

```

Try it online!

Frankly, I'm just stoked it's below 200 bytes.

# Answer
> 0 votes
# Ahead, 34 bytes

Contains trailing newline.

```
"AWSALILAND"u$l<
~dW:k-A':\N\0<~n@

```

Try it online!

# Answer
> 0 votes
# Retina, 56 bytes

```
K`AWSALILAND
L`.
W
23*W
S
19*S
L
22*L
I
9*I
D
4*D
N
14*N

```

**Explanation:**

```
K`AWSALIAND

```

Sets the working string to AWSALIAND

```
L`.

```

Puts each character onto a new line. `L` is a list, and each item is found by the regex `/./`.

```
character
n*character

```

Replace all occurences of character with n lots of the character.

Try it online!

# Answer
> 0 votes
# Poetic, 470 bytes

```
any days i wish i could&i say i could,i can not
still at the age where,a lot of times,i can not raise my own money
guess i got myself overly exhausted,or spent
no pun is meant
i was a child of ten,a child of ten
a thing i know:i saved a buck a month
m-one-y,m-one-y,m-ones-y
still,i had a dream,i had a vision
oh my god,what a dream
i had a vision i was rich
at first im like:o,i have a payoff,o
however,truly i am not especially pleased
indeed,o,i see i am scared of it

```

Try it online!

I don't especially like the fact that I have to hardcode `AWSALILAND` (mostly because I don't know what that *means*). But at least this works.

# Answer
> 0 votes
# Husk, 19 bytes

```
mSRo-64c"AWSALILAND

```

Try it online!

# Answer
> 0 votes
# Deadfish~, 284 bytes

```
{iiiiii}iiiiic{ddddd}dddddc{{i}dd}ddd{cc}ccc{{d}ii}iiic{{i}ddd}iii{c}ccccccccc{{d}iii}dddc{iiiii}iiiiic{ddddd}dddddc{iiiiii}iiiiii{c}cc{dddddd}ddddddc{iiiiii}iiiccccccccc{dddddd}dddc{iiiiii}iiiiii{c}cc{dddddd}ddddddc{iiiii}iiiiic{ddddd}dddddc{{i}ddd}dd{c}cccc{{d}iii}iic{iiiiii}ddcccc

```

Try it online!

# Answer
> 0 votes
# CSASM v2.2.1.2, 162 bytes

```
func main:
lda 0
sta $1
lda "AWSALILAND"
.lbl a
push $a
conv ~arr:char
ldelem $1
dup
conv i32
push 64
sub
pop $2
conv str
push $2
mul
print.n
inc $1
push $1
push 10
sub
brtrue a
ret
end

```

**Commented and ungolfed:**

```
func main:
    ; Initialize $1 to zero and $a to the string "AWSALILAND"
    lda 0
    sta $1
    lda "AWSALILAND"

    .lbl loop
        ; Get the iteration char in the string
        push $a
        conv ~arr:char
        ldelem $1

        ; Duplicate it.  The first will be used as the string to print and the
        ;   second will be used for the string repetitions with "mul"
        dup

        ; Get the index in the alphabet (1..26) and put it in $2
        conv i32
        push 64
        sub
        pop $2

        ; Convert the character to a string, then perform the built-in string
        ;   repetitions with "mul"
        conv str
        push $2
        mul

        ; Print it with a newline appended
        print.n

        ; Truthy is non-zero, so the loop ends when ($1 + 1) - 10 == 0
        inc $1
        push $1
        push 10
        sub
        brtrue loop
    ret
end

```

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Additive Primes amongst first x Primes

text:
# Question
Title: Additive Primes amongst first x Primes
## Definition of Additive Primes:

* Numbers which have exactly 2 divisors are called *Prime* numbers.
* Numbers which are prime and their sum of digits is also a prime number are called ***Additive Primes***

---

## Task:

Given an integer `x`, compute all the additive primes amongst the first `x` prime numbers, with `2` being considered both the first prime and additive prime number. The numbers are represented in base 10.

## Rules:

* The output consists of all the additive primes amongst the first `x` primes
* `0 < x < 151`, for this challenge, for functionality purposes
* Since the additive primes are all integers, decimals are not allowed (e.g.: you should output `2`, not `2.0`) and they must not be displayed as a fraction.

---

## Examples:

`10 -> 2 3 5 7 11 23 29`

**Explanation:**

The first 10 primes are `2 3 5 7 11 13 17 19 23 29`, and only `2 3 5 7 11 23 29` have their sum of digits prime numbers, those being, respectively `2,3,5,7,2,5,11`, so they are **additive primes**

Following the explanation from `example 1`, other test cases may be:

```
2 -> 2 3

25 -> 2 3 5 7 11 23 29 41 43 47 61 67 83 89

7 -> 2 3 5 7 11

```

---

## Leaderboard:

```
var QUESTION_ID=112088,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left;font-family:"Helvetica Neue"}table thead{font-weight:700;font-family:"Helvetica Neue"}table td{padding:5px;font-family:"Helvetica Neue"}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

---

**NOTE:** Please read the newly-edited rule 1, it brings changes to the output format slightly

---

Your code should be as short as possible, since this is , so the shortest answer in bytes wins. Good luck!

# Answer
## Pyke, ~~9~~ 7 bytes

```
~p>#Yss

```

Try it online!

The single byte `is_prime` was only pushed 3 hours ago. Github commit.

```
~p      -    All the prime numbers
  >     -   first input of them
   #Yss -  filter(^)
    Y   -     digits(^)
     s  -    sum(^)
      s -   is_prime(^)

```
> 8 votes

# Answer
# Röda, ~~136~~ 135 bytes

```
f n{P=[2]S=[2]seq 3,863|{|i|{P|{P+=i;s=0;((""..i)/"")|parseInteger _|s+=_;S+=i if[s in P and not(i in S)]}if{|p|[i%p>0]}_}if[#P<n]}_;S}

```

Try it online!

It's a function that returns the requested additive primes.

Usage: `main { f(25) | print ap for ap }` The code uses version 0.12, which is in branch `roda-0.12`.

Ungolfed:

```
function f(n) {
    primes := [2]
    ultraprimes := [2]
    seq(3, 863) | for i do
        break if [ #primes = n ]
        if [ i%p != 0 ] for p in primes do
            primes += i
            sum := 0
            ((""..i)/"") | parseInteger _ | sum += digit for digit
            ultraprimes += i if [ sum in primes and not (i in ultraprimes) ]
        done
    done
    ultraprimes
}

```
> 9 votes

# Answer
## Python 2, 124 118 bytes

With help from Riker:

```
n,f,P=input(),filter,lambda n:all(n%i for i in range(2,n))
f(lambda x:P(sum(map(int,`x`)))&P(x),f(P,range(2,n*n))[:n])

```

Original:

```
n,o,c,P=input(),0,2,lambda n:all(n%i for i in range(2,n))
while o<n:
 o+=P(c)
 if P(sum(map(int,`c`)))and P(c):print c
 c+=1

```

Checking primality in Python ain't fun.
> 8 votes

# Answer
## Mathematica, ~~61~~ 47 bytes

```
Prime@Range@#~Select~PrimeQ@*Tr@*IntegerDigits&

```
> 5 votes

# Answer
# Perl 6, 53 bytes

```
{grep *.comb.sum.is-prime,grep(*.is-prime,0..*)[^$_]}

```

Try it

## Expanded:

```
{
  grep
    *.comb.sum.is-prime, # find the ultra primes from:
    grep(
      *.is-prime,        # find the primes
      0..*               # from all integers
    )[ ^$_ ]             # grab only the first x primes
}

```

If this challenge were changed so that you took the first *x* ultraprimes this could be shortened to just

```
{grep({($_&.comb.sum).is-prime},0..*)[^$_]}

```
> 5 votes

# Answer
# Python 2, ~~96~~ 87 bytes

```
p=-input(),0;m=k=1
while sum(p):
 m*=k*k;k+=1;p+=m%k,
 if m%k*p[int(`k`,36)%35]:print k

```

*Thanks to @xnor for golfing off 9 bytes!*

Try it online!
> 5 votes

# Answer
# Jelly, 10 bytes

```
ÆNDS$€ĖÆPM

```

**Try it online!**

### How?

A slightly different approach...

```
ÆNDS$€ĖÆPM - Main link: n (>0)           e.g. 10
ÆN         - nth prime number                 29
     €     - for each in range(1,nth prime)   [1,    2,    3,   ..., 27,    28,     29]
    $      - last two links as a monad
  D        -     decimal digit list          [[1],  [2],  [3],  ...,[2,7], [2,8],  [2,9]]
   S       -     sum                          [1,    2,    3,   ..., 9,     10,     11]
      Ė    - enumerate                       [[1,1],[2,2],[3,3],...,[9,27],[10,28],[11,29]]
       ÆP  - is prime? (vectorises)          [[0,0],[1,1],[1,1],...,[0,1], [0,0],  [1,1]]
         M - indices of maximal elements     [       2,    3,   ...,                29]

```
> 4 votes

# Answer
# 05AB1E, 9 bytes

```
ÝØ¨vySOp—

```

Uses the **CP-1252** encoding. Try it online!
> 3 votes

# Answer
# Jelly, 11 bytes

```
ÆN€DS$ÆP$Ðf

```

Try it online!

Explanation:

```
ÆN€DS$ÆP$Ðf Main link (args: z)
ÆN€         Generate first z primes.
   DS$      Take the digital sum.
      ÆP    Check if it's prime.
        $   Join last two links and make a monad.
         Ðf Only keep elements which conform to the criterion above.
```

**I got outgolfed.**
> 3 votes

# Answer
# MATL, ~~15~~ 13 bytes

*2 bytes saved thanks to @Luis*

```
:Yq"@V!UsZp?@

```

Try it at **MATL Online**

**Explanation**

```
        % Implicitly grab input as a number (N)
:       % Create an array [1...N]
Yq      % Get the k-th prime for each element k in that array
"       % For each element in this list
  @     % Get the current element
  V!U   % Break it into digits
  s     % Sum up the digits
  Zp    % Determine if this is a prime number
  ?@    % If it is, push the value to the stack
        % Implicit end of for loop and implicit display of the stack

```
> 2 votes

# Answer
# Fig, \\$12\log\_{256}(96)\approx\\$ 9.877 bytes

```
FtxFmC@p'pSf

```

Try it online!

Explanation:

```
 t            # take the first
  x           # x items from
    mC        # all positive integers
   F          # filtered by
      @p      # is prime,
F       '     # then filter those by
          S   # the sum of
           f  # the digits
         p    # is prime

```
> 2 votes

# Answer
# Ohm, 10 bytes (CP437)

```
@▓_π;░_}Σp

```

This would be much shorter if I had vectorization or a component for the first N primes, but alas, I did not before this challenge (but I do now!).

Explanation:

```
@▓_π;░_}Σp    Main wire, arguments: a

@▓  ;         Map...over the range (1..n)
  _π            nth prime
     ░        Select from ToS where...
      _}Σ       The sum of all digits
         p      is prime

```
> 1 votes

# Answer
# Bash \+ coreutils, 97 bytes

```
p()(factor $1|wc -w)
for((;++n,c<$1;)){((`p $n`-2||(c++,`p $[n%10+n/10%10+n/100]`-2)))||echo $n;}

```

Try it online!
> 1 votes

# Answer
# PowerShell, 120 bytes

```
for($n=$args[0];$n){for(;'1'*++$i-notmatch($s='^(?!(..+)\1+$)..')){}if('1'*([char[]]"$i"-join'+'|iex)-match$s){$i};$n--}

```

Try it online!

Prime checking in PowerShell sucks.

The outer `for` loop goes from input `$n` down to `0`. In the inner loop, we use a prime generator on `$i`, then check `if` the digit-sum (`-join'+'|iex`) is also a prime. If so, we put `$i` on the pipeline. In either case, we decrement `$n--` and the outer `for` loop continues. The resulting `$i`s are gathered from the pipeline and an implicit `Write-Output` happens at program completion.
> 1 votes

# Answer
# Bash + GNU utilities + bsd-games package, 69

```
primes 2|sed -rn 'h;s/./ + &/g;s/.*/expr &|factor/e;/\w\s/!{x;p};'$1q

```

Try it online.
> 1 votes

# Answer
# Pari/GP, 59 bytes

```
f(x)=[p|p<-vector(x,i,prime(i)),isprime(vecsum(digits(p)))]

```

Try it online!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
ʁǎ'∑æ

```

Try it online, or verify more test cases.

Explanation:

```
ʁ      # Range from 0 to n-1
 ǎ     # Nth prime (vectorising)
  '    # Filtered by:
   ∑   #   The digit sum
    æ  #   Is prime

```
> 1 votes

# Answer
# MathGolf, 9 bytes

```
♪╒g¶<gÅΣ¶

```

Try it online.

**Explanation:**

Since the input is guaranteed to be within the range \\$\[1,150\]\\$, where the \\$150^{th}\\$ prime is \\$877\\$, we'll use this to our advantage. (Although using `ó` (\\$2^n\\$ builtin using the implicit input) instead of  would have worked as well, but would be way too slow for larger inputs.)

```
♪╒         # Push a list in the range [1,1000]
  g        # Filter it by:
   ¶       #  Check if the number is a prime
    <      # Then only keep the first (implicit) input amount of prime numbers
     g     # Filter it again,
      Å    # using 2 characters as inner code-block:
       Σ   #  Get the digit-sum of the current integer
        ¶  #  Check if it's also a prime
           # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# MATL, 13 bytes

```
:YqtFYA!XsZp)

```

Try it at **MATL Online!**

### Explanation

```
:      % Range [1 2 ... n], where n is implicit input
Yq     % Array of first n prime numbers
t      % Duplicate
FYA    % Convert to decimal digits. Gives a matrix, where each original
       % number corresponds to a row. Left-pads with zeros if needed
!Xs    % Sum of rows
Zp     % Is prime? (element-wise)
)      % Use as logical index into the array of the first n prime numbers
       % Implicitly display

```
> 0 votes

# Answer
# Husk, 8 bytes

```
fȯṗΣd↑İp

```

Try it online!
> 0 votes

# Answer
# Japt, 12 bytes

```
Èj}jU fÈìx j

```

Try it
> 0 votes

# Answer
# Factor \+ `math.primes math.unicode math.text.utils`, 47 bytes

```
[ nprimes [ 1 digit-groups Σ prime? ] filter ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes an integer from the data stack as input and leaves a sequence of integers on the data stack as output.

* `nprimes` Obtain a list of the first n primes.
* `[ ... ] filter` Take elements from the list that match a predicate.
* `1 digit-groups` Obtain a list of digits from an integer.
* `Σ` Sum a sequence.
* `prime?` Is it prime?
> 0 votes

# Answer
# 05AB1E, 6 bytes

```
ÅpʒSOp

```

Try it online or verify all test cases.

**Explanation:**

```
Åp      # Get a list of the first (implicit) input amount of primes
  ʒ     # Filter this list by:
   S    #  Convert the prime to a list of digits
    O   #  Sum them together
     p  #  Check if this sum is a prime
        # (after which the filtered list is output implicitly as result)

```
> 0 votes

---
Tags: code-golf, math, number, number-theory, primes
---


title: Twisting Words!

text:
# Question
Title: Twisting Words!
# Twisting Words!

Given a string and a positive integer. You must twist the string, back and forth.

### Example Input / Output

Input

```
Programming Puzzles & Code Golf
4

```

Output

```
Prog
mmar
ing
zzuP
les
oC &
de G
 flo

```

## Input

The input can be taken in through STDIN, or function argument. The input will consist of a string and a positive integer, *n*. The integer will determine the length of each twisted line.

The string is twisted back-and-forth. An input of `HELLO, WORLD!` and 5 would look like:

## Output

The output will be the twisted text. It may not any trailing whitespace. If the input string length is not divisible be the line length, add a space until the line is filled:

An example of this:

Input

```
Hello, World!
5

```

Output (Note the whitespace at the very end)

```
Hello
roW ,
ld!

```

# Answer
# Pyth, ~~19~~ 15

```
VPc+z*dQQ_W~!ZN

```

Pre-pads the string, then reverses each other line as it prints it. The padding is equal to the size of the box, but the last line after chopping up the input is discarded.

Try it here
> 12 votes

# Answer
# CJam, 19 bytes

```
q~1$S*+/W<{(N@Wf%}h

```

Input example:

```
5 "Hello, World!"

```

### Explanations

```
q~         e# Input n and the string.
1$S*+      e# Append n spaces to the string.
/W<        e# Split by each n characters, and remove the last chunk.
{          e# While the array of chunks isn't empty:
    (N     e# Extract the first chunk and push a newline.
    @Wf%   e# Reverse every chunk left in the array.
}h

```
> 7 votes

# Answer
## Python 2, 60

```
s,n=input()
d=1
while s:print(s+n*' ')[:n][::d];s=s[n:];d=-d

```

Takes `n` characters at a time from the from of `s`, printing them with a direction `d` that alternates between `1` and `-1`. For spacing on the last line, `s` is padded with `n` spaces at the end before it is chopped, which only affects it when it has fewer than `n` characters remaining.

A recursive solution would save a char (59) except that it leaves a trailing newline, which is not allowed.

```
f=lambda s,n,d=1:s and(s+n*' ')[:n][::d]+"\n"+f(s[n:],n,-d)

```
> 7 votes

# Answer
## Snowman 1.0.1, 91 bytes

```
{vg10vg|sB*#.'aGal'NdE'aaAaL|al!*+#5nS" "'aR'!#aCwR|.aC2aG:0aa|sP"
"sP'NdE|1aA.aNsP"
"sP;aE

```

Or all on one line (for aesthetics, or more specifically, anti-aesthetics), at the cost of 2 bytes:

```
{vg10vg|sB*#.'aGal'NdE'aaAaL|al!*+#5nS" "'aR'!#aCwR|.aC2aG:0aa|sP10wRsP'NdE|1aA.aNsP10wRsP;aE

```

This is way too short, for Snowman. (It's probably the shortest it can get, though; I worked on golfing this for a pretty long time.)

This has one caveat: it will exit with an error (but still produce the correct output) 50% of the time, when the last line is *not* reversed. (This is because I use `ag` to group the array elements in groups of two so that I can reverse every other one, but I don't check whether the last element has both expected elements, so it'll try to access a nonexistent element if there are an odd number of lines.)

Ungolfed / explanation:

```
{vg10vg|sB*#      // get input, convert second string to number and store
.'aG              // split string into groups of n chars
al'NdE'aaAaL      // take out the last element of the array
|al!*+#5nS" "'aR  // subtract its length from 5, repeat that many spaces
'!#aCwR|.aC       // concat spaces to last el. and that back to the array
2aG               // split in groups of 2, so we can reverse every other string
// for each sub-group in the array of groups...
:
    0aa|sP10wRsP         // print the first element as is
    'NdE|1aA.aNsP10wRsP  // print the second element, reversed
;aE

```
> 5 votes

# Answer
# Haskell, ~~83~~ 75 bytes

```
(id!)
(f![])_=[]
(f!l)n=f(take n$l++cycle" ")++'\n':((f.reverse)!drop n l)n

```

Simple `chunksOf` implementation with take and drop, applying an even or odd number of reverses to the output as we go.

Thanks to @BMO for five bytes and @ØrjanJohansen for three bytes!

Try it online!
> 5 votes

# Answer
# , 22 15 13 bytes

```
]`|."1@(]\)~-

```

*-2 bytes thanks to xash*

Note the above solution requires J901, which allows you to apply cyclic gerunds using the rank `"` conjuntion. TIO uses an older version, so to run this one you have to download J.

However, my previous solution of 15 bytes will work on TIO:

## 15 bytes

```
([]`|.\[:,]\)~-

```

Try it online!

Finally, another 15 byte alternative, thanks to @Marshall and based on a trick from @ngn, is:

```
([:|.@]/\]\)~-

```
> 5 votes

# Answer
# Stuck, ~~42~~ ~~41~~ ~~40~~ 38 Bytes

This is a wee bit too long, probably will try to golf more!

```
tg;_lu_@%u;-_0G<*' *+0GKE"];2%;Y_Y?p":

```

Input should be like `"string"|n`.

Explanation:

```
tg                 # Take input, place each item on stack, save the int to variable stack
;_l                # Swap the top two items, duplicate the string and obtain length
u_@%               # Rotate to the left, duplicate, rotate right and take mod
u;-                # Rotate left, swap the top two and subtract from each other
_0G<*              # duplicate this value, check if less than stored int and multiply
' *+               # Push space onto stack n times, append to starting string
0GKE               # Split this string into segments, and enumerate
"];2%;Y_Y?p":      # For each segment, determine if should be reversed, and print

```
> 4 votes

# Answer
# APL (Dyalog Unicode), 19 bytes

```
{↑⊢∘⌽\↓↑⍵⊆⍨⌈⍺÷⍨⍳≢⍵}

```

Try it online!

Took the `⊢∘⌽\` trick from ngn's brilliant answer to the boustrophedonise challenge.

After realising that my submission breaks for lines with leading newlines, I have added two more bytes. Below is the older submission.

# APL (Dyalog Unicode), 17 bytes

```
{↑⊢∘⌽\⍵⊆⍨⌈⍺÷⍨⍳≢⍵}

```

Try it online!
> 4 votes

# Answer
# Perl, 87 bytes

```
sub f{$_=@_[0].$"x(@_[1]-1);$a.=(($i++&1?reverse$1:$1).$/)while/(.{@_[1]})/g;chop$a;$a}

```

Old version (prints a trailing newline):

```
sub f{$_=@_[0].$"x(@_[1]-1);print(($i++&1?reverse$1:$1).$/)while/(.{@_[1]})/g}

```

String is passed as a function argument with no trailing newline. Call like this:

```
$_=<>;chomp;print f($_,5);

```
> 3 votes

# Answer
## PowerShell, 102 Bytes

```
param($s,$i)$l=$s.Length;$s+' '*($i%$l)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$l..0]-join''))[$r]}

```

Invoked as follows (if saved to file `CodeGolf55051.ps1`)

```
.\CodeGolf55051.ps1 -s '1234567890' -i 4

```

---

## Previous Attempts

(longer or invalid)

**PowerShell, 110 Bytes**

```
param($s,$i)$l=$s.Length;$s+' '*(($i-$l%$i)%$i)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$l..0]-join''))[$r]}

```

**PowerShell, 111 Bytes**

```
param($s,$i)$s+' '*(($i-$s.Length%$i)%$i)-split"(.{$i})"|?{$_}|%{$r=-not$r;@($_,($_[$_.length..0]-join''))[$r]}

```

**Explanation**

```
param($s,$i)                         #Take input text (s) and column width (i)
$s                                   #take the user entered string
+ ' ' * (($i - $s.Length % $i) % $i) #add the least number of spaces required to make its length divisible by i
-split"(.{$i})"                      #break it into chunks of i characters in length
| ?{$_}                              #skip any blank lines created in the process
| %{                                 #for each line
    $r = -not $r;                    #    toggle a boolean value
    @(                               #    define an array
        $_                           #    index 0 = the string going forwards
        ,($_[$_.length..0] -join '') #    index 1 = the string reversed (by taking each character from the last to the first, then joining them)
    )[$r]                            #    if our boolean value is false take the forward string (index 0), if true take the backwards one (index 1)
}                                    #next

```

**PowerShell, 180 Bytes**

```
param($s,$i)$x="`${0}|{1}|`${2}";$w=$x;1..$i|%{$w=$w-f$_,$x,($i+$_)};$w=$w-replace'\||\${.*}';$r=$w-replace'\$\d+','(.)?';$s+' '*($i-$s.Length%$i)-replace$r,$w-split"(.{$i})"|?{$_}

```

**PowerShell, 196 Bytes**

```
param($s,$i)$x="{0}|{1}|{2}";$w=$x;1..$i|%{$w=$w-f$_,$x,($i+$_)};$w=$w-replace'(\d+)','$$$1'-replace'\||{.*}';$r=$w-replace'\$\d+','(.)?';$s+' '*($i-$s.Length%$i)-replace$r,$w-split"(.{$i})"|?{$_}

```

**Explanation**

```
param ($s, $i)                      #Take input text (s) and column width (i)

$x = "{0}|{1}|{2}"                  #Define string format which takes 3 entries and pipe delimits them

$w = $x                             #initialise our replacement regex with this format
1..$i | %{                          #for 1 to the specified column width
    $w = $w -f $_, $x, ($i + $_)    #update the regex 1|{...}|5, 1|2|{...}|6|5, etc
}                                   #resulting in w = 1|2|3|4|{...}|8|7|6|5
$w = $w -replace '(\d+)', '$$$1'    #now prefix the numbers with a dollar (so they're regex replacement variables)
        -replace '\||{.*}'          #and remove the delimiters and superfluous `{...}` left from our middle insertion routine

$r = $w -replace '\$\d+', '(.)?'    #then create the match pattern by replacing the variables with optional single character captures

$s                                  #now take the user entered string
    + ' ' * ($i - $s.Length % $i)   #add the least number of spaces required to make its length divisible by i
    -replace $r, $w                 #perform a replacement using the regex match and replace patterns created above
    -split "(.{$i})"                #then split the string into blocks of length i
    | ?{$_}                         #removing any blank lines created in the process

```

(`{...}` in the above comments is actually `{0}|{1}|{2}`; I put `{...}` for improved readability.

**Powershell, 120 Bytes** (invalid)

```
param($s,$i)$s + ' ' * ($i-$s.Length%$i) -replace '(.{4})?(.)(.)(.)(.)',"`$1`n`$5`$4`$3`$2`n" -split "`n" | ?{$_ -ne ""}

```
> 3 votes

# Answer
## Mumps, 86 bytes

```
R I,S,! S P=$L(I),$P(I," ",P)=P F Q=1:S:P S F=$E(I,Q,Q+S-1),P='P W $S('P:F,1:$RE(F)),!

```

Although it could be 2 bytes shorter if you remove the first ',!' characters in the R statement (read from STDIN); that adds a carriage return between the input and output. If that wasn't there, the output is technically correct, but the first line would appear appended to the input string. *\[\[ The standard Mumps terminal that I use has no local echo. \]\]* As it sits, here's the test:

```
R I,S,! S P=$L(I),$P(I," ",P)=P F Q=1:S:P S F=$E(I,Q,Q+S-1),P='P W $S('P:F,1:$RE(F)),!
ABCDEFGHIJKLMNOPQRSTUVWXYZ1236
ABCDEF
LKJIHG
MNOPQR
XWVUTS
YZ123

```

Also note, there's actually a carriage return / Enter keypress between the '123' and the '6' at the end of the input. *\[\[ The local echo thing again. \]\]*

If anyone's interested I can describe what's going on with the code; but I do realize there's not a ton of Mumps enthusiasts out there... :-)
> 3 votes

# Answer
## Perl 5, 51 bytes

```
$_.=$"x(($-=<>)-1);say--$|?$_:~~reverse for/.{$-}/g

```

Try it online!
> 3 votes

# Answer
## Clojure, 83 bytes, 87 bytes, 79 bytes

```
(fn[n s](map #(apply str(% %2))(cycle[#(or %)reverse])(partition n n(repeat\ )s))))

```

several corrections after comments below, thank you Ørjan.

Try it online!

Clojure seems often sadly absent from code golfing answers. It certainly can not compete in byte length with golfing languages, but I think the total absence is somewhat unwarranted.

Explanation:

* in-data, two arguments a number and a string
* start by running clojure built-in function partition on string `s` chunking it into a sequence of lists of characters where the lists have length `n`. The last chunk will be padded with spaces to length `n` using the "pad collection" returned from `(repeat " ")` which returns an infinite lazy sequence of spaces
* we then call map with three arguments:
    + an anonymous function (the `#(..)`)
    + an infinite alternating lazy sequence of functions `#(or %)` which functions like the identity function and reverse (i.e. `[#(or %) reverse #(or %) reverse ...]`) as returned by cycle.
    + the chunked up lazy sequence of lists returned by partition.
* finally the anonymous function `#(apply ...)`:
    + calls either `identity` or `reverse` alternatingly on a chunk. This is done via the `(% %2)` expression which calls the function sent in as the first argument to the anonymous function \[i.e. `identity` or `reverse`\] using the second argument \[i.e. the chunk\] to the anonymous function as the argument to the call.
    + calls `(apply str ...)` to convert the list of characters into a string
* the outer function returns a lazy sequence of strings

one trick we use here is that a lot of clojure functions like `map` take an arbitrary number of collections as args, i.e. `(map f coll1 coll2 coll3 ...)` where the function f just needs to accept as many arguments as there are collections. In this case we send in two collections, a collection of alternating function references and the chunked up string.
> 3 votes

# Answer
# Python 3, ~~110~~ ~~108~~ ~~107~~ 103 bytes

```
def a(s,n):l=len(s)//n+1;s+=' '*(len(s)-l);print('\n'.join([s[x*n:n*x+n][::(-1)**x]for x in range(l)]))

```

(looking at other answers), with `rjust`: ~~95~~ ~~93~~ ~~92~~ 90 bytes

```
def a(s,n):print('\n'.join([s[x*n:n*x+n][::(-1)**x].rjust(n)for x in range(len(s)//n+1)]))

```
> 3 votes

# Answer
# Lua, ~~91~~ ~~88~~ ~~88~~ ~~84~~ ~~83~~ 82 bytes

Old version:

```
a=arg for i=1,#a[1],a[2]do s=a[1]:sub(i,i+a[2]-1)print(d and s:reverse()or s)d=not d end

```

New version:

```
arg[1]:gsub((".?"):rep(arg[2]),function(s)print(d and s:reverse()or s)d=not d end)

```
> 2 votes

# Answer
# Haskell, 108 bytes

```
(#)=splitAt
s!n=let(a,t)=n#s;(b,u)=n#t in a:reverse b:(u!n)
s%n=unlines$takeWhile(any(>' '))$(s++cycle" ")!n

```

That's sort of long, jeez. Here it is in action:

```
*Main> putStrLn $ "Programming Puzzles & Code Golf" % 4
Prog
mmar
ing
zzuP
les
oC &
de G
 flo

```
> 2 votes

# Answer
# Python 2, 109 bytes

Had to add padding with spaces for the last line to be correct.

**Try it here**

```
I,c=input()
I+=(c-len(I)%c)*" "
L=[]
i=0
while I:s=I[:c];L+=[[s,s[::-1]][i%2]];i+=1;I=I[c:]
print"\n".join(L)

```
> 2 votes

# Answer
# Q, ~~64~~ 56 bytes

```
{c::neg y;-1(til(#)l){$[x mod 2;c$(|:)y;y]}'l:y cut x;}

```
* `{}` is a function that should be called as `{}[x;y]`.
    + `x` will be the string.
    + `y` will be the length of the resulting lines.

Test:

```
{c::neg y;-1(til(#)l){$[x mod 2;c$(|:)y;y]}'l:y cut x;}["Programming Puzzles & Code Golf";4]
Prog
mmar
ing
zzuP
les
oC &
de G
 flo

```

**edit**: Used shorter functions as inspired by the other q answer by @tmartin
> 2 votes

# Answer
# Python 2, 82 75 bytes

```
s,n=input()
k=0
while k<=len(s):print s[k:k+n].ljust(n)[::1-2*(k/n%2)];k+=n

```

I couldn't comment on @willem but I made his code smaller.

Try here Try here
> 2 votes

# Answer
# O, 60 bytes

```
z""/rlJ(Q/{n:x;Q({+}dxe{`}{}?p}drQJQ%-{' }dJQ/e{r}{}?Q({o}dp

```

My very first O program, and a long one at that!

Live demo.
> 2 votes

# Answer
# JavaScript ES6, 123 bytes

```
var t=(s,n)=>{for(var d=1,i=0,o='',l=s.length;i<l;i++){o+=d?s[i]:s[i-i%n+n-1-i%n]||' ';if(i%n==n-1){d=!d;o+='\n'}}return o}

```

Call with `t(input_string, twist_length)`, which returns the output string.
> 2 votes

# Answer
# Perl, 72 bytes

```
perl -p0e's/\n(.*)/$"x($1-$-[0]%$1)/e;s/.{$1}/($i++%2?reverse$&:$&)."\n"/ge;chop'

```

70 bytes, plus 2 bytes for `-p0`.

Demo:

```
$ echo -en 'Hello, World!\n5' | perl -p0e's/\n(.*)/$"x($1-$-[0]%$1)/e;s/.{$1}/($i++%2?reverse$&:$&)."\n"/ge;chop'
Hello
roW ,
ld!  $

```

Note that the input read from STDIN cannot end with a newline (that would cost 2 extra bytes).

Explanation:

```
perl -p0e'  # Read from STDIN, splitting on null bytes,
            # and print $_ automatically at the end

    s/
        \n(.*)  # Replace everything after first newline,
                # capturing wrap length in $1...
     /
        $"x($1-$-[0]%$1)  # ...with spaces until the total length of $_ is
                          # a multiple of $1 (i.e. right-pad with spaces)
     /e;

    s/
        .{$1}  # Replace series of $1 contiguous chars...
     /
        ($i++%2?reverse$&:$&)."\n"  # ...alternately with themselves or in
                                    # reverse, with a trailing newline
     /ge;

    chop'  # Remove final newline

```
> 2 votes

# Answer
# Japt `-R`, 9 bytes

```
òV ËzEÑÃù

```

Try it
> 2 votes

# Answer
# Python 3, 64 bytes

Try Online

```
def a(s,n,x=1):
 while s:print(s[:n].rjust(n)[::x]);s=s[n:];x=-x

a('Programming Puzzles & Code Golf',4)

```

Step 1: Print the first n bytes of the string (flag = 1 so normal order) Step 2: Trim the string by n bytes Step 3: Flip the flag to -1 Repeat the process until string is empty

Note that flag flips to +1 and -1. When it goes to -1, it prints in reverse order
> 2 votes

# Answer
## PHP, 135 bytes

Takes two command-line arguments as shown with `$argv`.

```
<? foreach($a=str_split($s=$argv[1],$n=$argv[2])as$k=>&$v)$v=$k%2?$v:strrev($v);echo implode("\n",$a).str_repeat(' ',$n-strlen($s)%$n);

```
> 1 votes

# Answer
## CoffeeScript, 131 bytes

This seems too long.

```
f=(s,n,r=l=s.length,i=0,z='')->(t=s[i...i+=n].split '';t=t.reverse()if r=!r;z+=t.join('')+(i<l&&'\n'||' '.repeat n-l%n))while i<l;z

```
> 1 votes

# Answer
# Julia, 104 bytes

```
f(s,n)=(L=length(s);L+=L÷n;j=0;for i=1:n:L-n+1 x=rpad(s,L)[i:i+n-1];println(j%2<1?x:reverse(x));j+=1end)

```

Ungolfed:

```
function f(s::String, n::Int)
    L = length(s) + length(s) ÷ n
    j = 0
    for i = 1:n:L-n+1
        x = rpad(s, L)[i:i+n-1]
        println(j % 2 == 0 ? x : reverse(x))
        j += 1
    end
end

```
> 1 votes

# Answer
# Python 2, 86 bytes

Here's my answer (borrowing some input processing from @mbomb007). Unfortunately can't define the len(s) as a variable as the length of the string changes after padding with spaces. Now also using rjust() instead of ljust() as @AlexN suggested.

```
s,n=input()
k=n
while k<=len(s):print s[k-n:k]+'\n'+s[k+n-1:k-1:-1].rjust(n);k+=2*n

```
> 1 votes

# Answer
## Shell/Bash, 135 bytes

```
s=0;while true;do ((s%($2*2)))&&{ echo "${1:s:$2}"|rev;s=$((s+$2)); }||{ echo "${1:s:$2}";s=$((s+$2)); };((s>=${#1}))&&{ exit 1; };done

```
> 1 votes

# Answer
# Python 3, 101 bytes

```
t,x=eval(input())
print("\n".join([t[c:c+x].ljust(x)[::1-2*(int(c/x)%2)] for c in range(0,len(t),x)]))

```

Try it here
> 1 votes

# Answer
# q, 46

```
{-1@neg[y]$@[a;(&)(til(#)a:y cut x)mod 2;|:];}

```

.

```
q){-1@neg[y]$@[a;(&)(til(#)a:y cut x)mod 2;|:];}["Programming Puzzles & Code Golf";4]
Prog
mmar
ing
zzuP
les
oC &
de G
 flo

```
> 1 votes

# Answer
# Coffeescript, 151 bytes

```
f=(s,n)->r="";d=n;i=0;_="\n";u=" ";l=s.length;(d--and(r+=s[i]or u;++i)or(r+=_;r+=s[c]or u for c in[i+n-1..i];i+=d=n;r+=_ if i<l))while i<(l/n+1>>0)*n;r

```

Too much =(
> 1 votes

# Answer
# Bash, ~~83~~ 74

```
for((i=0;i<${#1};i+=$2));do b=cat;((i/$2%2))&&b=rev;echo ${1:i:$2}|$b;done

```

This alternates between `cat` and `rev` for substrings of the first argument with a length of the second argument.

Special variables used include

* `${#1}` (the length of the string `$1`)
* `((i/$2%2))` (an arithmetic expression dividing incrementor `$i` by `$2` and then taking its modulo to determine odd vs even, which dictated whether or not to use `rev`)
* `${1:i:$2}` (substring of `$1` starting at position `$i` with a length of `$2`).
> 1 votes

# Answer
# JavaScript ES6, 113 bytes

Just my own crack at my own question. It will add spaces so it is divisible by `n`, that way it's simply splitting and reversing.

```
(s,n)=>(s+' '.repeat(n-s.length%n)).match(eval(`/.{1,${n}}/g`)).map((l,i)=>i%2?[...l].reverse().join``:l).join`
`

```
> 1 votes

# Answer
# C (gcc), ~~145~~ 141 bytes

Not allowing trailing whitespace made it clunkier than otherwise.

Thanks to ceilingcat for the tip that led me on the track to save 4 bytes.

```
f(s,n,l,i,j)char*s;{for(l=strlen(s),i=0;i<l;i+=2*n)if(printf("%-*.*s\n",n,n,s+i),i+n<l){for(j=i+2*n;j>i+n;)putchar(l/j--?s[j]:32);puts("");}}

```

Try it online!
> 1 votes

# Answer
## Groovy, 68 bytes

```
f=-n;s.eachMatch(/.{1,$n}/){printf "%${f}s%n",f>0?it[-1..0]:it;f=-f}

```

revised after I realized the initial version didn't handle padding correctly.

Try it online!
> 1 votes

# Answer
# Java 8, ~~197~~ ~~146~~ 136 bytes

```
s->n->{String r="",t,u;for(int l=s.length,i=0,j;i<l/n*n+n;r+=t+"\n",i=j)for(t="",j=i;j<i+n;t=j++/n%2<1?t+u:u+t)u=j<l?s[j]:" ";return r;}

```

Try it online.

**Explanation:**

```
s->n->{                 // Method with String and integer parameters and String return-type
  String r="",          //  Result-String, starting empty
         t,u;           //  Temp-Strings
  for(int l=s.length,   //  Length of the input-String
      i=0,j;i<l/n*n+n   //  Loop `i` in the range [0, `l` + whatever to make blocks of `n`)
      ;                 //    After every iteration:
       r+=t+"\n",       //     Append the result-String with `t` and a new-line
       i=j)             //     And set `i` to `j`
    for(t="",           //   Reset `t`
        j=i;j<i+n;      //   Inner loop `j` in the range [i, i+n)
        ;t=j++/n%2<1?   //     After every iteration: If the k'th block of `n` is even:
            t+u         //      Append `u` to `t`
           :            //     Else (it's odd):
            u+t)        //      Prepend `u` to `t`
      u=j<l?            //    If `j` is still within bounds:
         s[j]           //     Set `u` to the current character
        :               //    Else:
         " ";           //     Set `u` to a space
  return r;}            //  Return the result-String

```
> 1 votes

# Answer
# Japt, 14 bytes

```
óV y £Yv ?X:Xw

```

Try it online!
> 1 votes

# Answer
# Pip, 34 bytes

```
Fla.sXb-#(@RVa<>b)<>b{Po?lRVlo!:o}

```

Similar approach as to my Boustrophedonise answer, but with padding and splitting the string.

Try it online!
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
ô0UεRDg²s-úXÈiR}X>U}}»

```

Try it online!

Bring on the golfing suggestions!
> 1 votes

# Answer
# Jelly, 8 bytes

```
sz⁶ZUÐeY

```

Try it online!

```
s           Slice the left argument into pieces (right argument) long.
 z          Zip it with filler
  ⁶         " ",
   Z        zip it back,
    U       reverse the slices
     Ðe     at even 1-indices,
       Y    and join on newlines.

```
> 1 votes

# Answer
# Brachylog, 20 bytes

```
⟨{ġ|,Ṣ↰}lᵛ⟩{i↔ⁱ⁾}ᶠ~ṇ

```

Try it online!

Takes input as a list `[string, slice length]`.

```
⟨{     }                To the string, apply the following predicate:
  ġ                     split it into slices of roughly equal length,
   |                    or
    ,Ṣ                  append a space
      ↰                 and recur.
        lᵛ⟩             ...such that each slice has the prescribed length.
                  ~ṇ    The output, split on newlines, is
           {    }ᶠ      every possible result from
            i           taking a slice with its 0-index
             ↔          and reversing
               ⁾        the slice
              ⁱ⁾        a number of times equal to the index.

```

I'm a bit ashamed to have only come up with this the moment I had finished explaining my previous solution:

# Brachylog, 22 bytes

```
{|,Ṣ↰}ʰġ₎z₂z{i↔ⁱ⁾c}ᶠ~ṇ

```

Try it online!

```
      ʰ                   Apply the following predicate to the input string:
{|                        leave it unchanged, or
  ,Ṣ                      append a space
    ↰}                    and recur.
       ġ                  Split the string into slices
        ₎                 of the given length (except maybe the last one).
         z₂z              Each slice has the same length.
                    ~ṇ    The output, split on newlines, is
            {     }ᶠ      every possible result from
             i            taking a slice with its 0-index
              ↔           and reversing
                ⁾         the slice
               ⁱ⁾         a number of times equal to the index
                 c        (then concatenating it, as the zipping exploded it).

```
> 1 votes

# Answer
## Python 3, 95 bytes

```
s,z=eval(input());p=0
while p<len(s):a=s[p:p+z].ljust(z);print(a[::-1] if p%(2*z) else a);p+=z

```

Try it here online: https://ideone.com/F4aY4d
> 1 votes

# Answer
# Vyxal `jr`, 5 bytes

```
ẇ↲⁽Ṙẇ

```

Try it online!

Explanation:

```
ẇ      # Get chunks of length n.
 ↲     # Pad each one with spaces to make it n chars long.
    ẇ  # On every second item, call:
  ⁽    # a one element lambda that
   Ṙ   # reverses it's input.
       # Join on newlines with j flag.

```
> 1 votes

# Answer
# Ruby, 80

```
->s,l{s+=' '*(l-s.size%l)
(s.size/l).times{|i|puts [x=s[i*l,l],x.reverse][i%2]}}

```

Online demo: http://ideone.com/w6o8PI
> 0 votes

---
Tags: code-golf, string
---