title: Draw a Houndstooth Pattern

text:
# Question
Title: Draw a Houndstooth Pattern
Write a program or function that takes in two positive integers, a width and a height, and draws an ASCII art houndstooth grid pattern with those dimensions using this 25×26 text grid as the base cell:

```
.......#.....#####.......
.......##.....#####......
.......###.....#####.....
.......####.....####.....
.......#####.....###.....
.......######.....##.....
.......#######.....#.....
.......########..........
####################.....
.####################....
..####################...
...####################..
....####################.
.....####################
#.....##############.####
##.....#############..###
###....#############...##
####...#############....#
#####..#############.....
.#####.#############.....
..##################.....
........#####............
.........#####...........
..........#####..........
...........#####.........
............#####........

```

So if the input was `2,1` the output would be:

```
.......#.....#####..............#.....#####.......
.......##.....#####.............##.....#####......
.......###.....#####............###.....#####.....
.......####.....####............####.....####.....
.......#####.....###............#####.....###.....
.......######.....##............######.....##.....
.......#######.....#............#######.....#.....
.......########.................########..........
####################.....####################.....
.####################.....####################....
..####################.....####################...
...####################.....####################..
....####################.....####################.
.....####################.....####################
#.....##############.#####.....##############.####
##.....#############..#####.....#############..###
###....#############...#####....#############...##
####...#############....#####...#############....#
#####..#############.....#####..#############.....
.#####.#############......#####.#############.....
..##################.......##################.....
........#####....................#####............
.........#####....................#####...........
..........#####....................#####..........
...........#####....................#####.........
............#####....................#####........

```

And if the input was `5,4` the output would be:

```
.......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####.......
.......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####......
.......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####.....
.......####.....####............####.....####............####.....####............####.....####............####.....####.....
.......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###.....
.......######.....##............######.....##............######.....##............######.....##............######.....##.....
.......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#.....
.......########.................########.................########.................########.................########..........
####################.....####################.....####################.....####################.....####################.....
.####################.....####################.....####################.....####################.....####################....
..####################.....####################.....####################.....####################.....####################...
...####################.....####################.....####################.....####################.....####################..
....####################.....####################.....####################.....####################.....####################.
.....####################.....####################.....####################.....####################.....####################
#.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.####
##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..###
###....#############...#####....#############...#####....#############...#####....#############...#####....#############...##
####...#############....#####...#############....#####...#############....#####...#############....#####...#############....#
#####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############.....
.#####.#############......#####.#############......#####.#############......#####.#############......#####.#############.....
..##################.......##################.......##################.......##################.......##################.....
........#####....................#####....................#####....................#####....................#####............
.........#####....................#####....................#####....................#####....................#####...........
..........#####....................#####....................#####....................#####....................#####..........
...........#####....................#####....................#####....................#####....................#####.........
............#####....................#####....................#####....................#####....................#####........
.......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####.......
.......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####......
.......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####.....
.......####.....####............####.....####............####.....####............####.....####............####.....####.....
.......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###.....
.......######.....##............######.....##............######.....##............######.....##............######.....##.....
.......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#.....
.......########.................########.................########.................########.................########..........
####################.....####################.....####################.....####################.....####################.....
.####################.....####################.....####################.....####################.....####################....
..####################.....####################.....####################.....####################.....####################...
...####################.....####################.....####################.....####################.....####################..
....####################.....####################.....####################.....####################.....####################.
.....####################.....####################.....####################.....####################.....####################
#.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.####
##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..###
###....#############...#####....#############...#####....#############...#####....#############...#####....#############...##
####...#############....#####...#############....#####...#############....#####...#############....#####...#############....#
#####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############.....
.#####.#############......#####.#############......#####.#############......#####.#############......#####.#############.....
..##################.......##################.......##################.......##################.......##################.....
........#####....................#####....................#####....................#####....................#####............
.........#####....................#####....................#####....................#####....................#####...........
..........#####....................#####....................#####....................#####....................#####..........
...........#####....................#####....................#####....................#####....................#####.........
............#####....................#####....................#####....................#####....................#####........
.......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####.......
.......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####......
.......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####.....
.......####.....####............####.....####............####.....####............####.....####............####.....####.....
.......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###.....
.......######.....##............######.....##............######.....##............######.....##............######.....##.....
.......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#.....
.......########.................########.................########.................########.................########..........
####################.....####################.....####################.....####################.....####################.....
.####################.....####################.....####################.....####################.....####################....
..####################.....####################.....####################.....####################.....####################...
...####################.....####################.....####################.....####################.....####################..
....####################.....####################.....####################.....####################.....####################.
.....####################.....####################.....####################.....####################.....####################
#.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.####
##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..###
###....#############...#####....#############...#####....#############...#####....#############...#####....#############...##
####...#############....#####...#############....#####...#############....#####...#############....#####...#############....#
#####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############.....
.#####.#############......#####.#############......#####.#############......#####.#############......#####.#############.....
..##################.......##################.......##################.......##################.......##################.....
........#####....................#####....................#####....................#####....................#####............
.........#####....................#####....................#####....................#####....................#####...........
..........#####....................#####....................#####....................#####....................#####..........
...........#####....................#####....................#####....................#####....................#####.........
............#####....................#####....................#####....................#####....................#####........
.......#.....#####..............#.....#####..............#.....#####..............#.....#####..............#.....#####.......
.......##.....#####.............##.....#####.............##.....#####.............##.....#####.............##.....#####......
.......###.....#####............###.....#####............###.....#####............###.....#####............###.....#####.....
.......####.....####............####.....####............####.....####............####.....####............####.....####.....
.......#####.....###............#####.....###............#####.....###............#####.....###............#####.....###.....
.......######.....##............######.....##............######.....##............######.....##............######.....##.....
.......#######.....#............#######.....#............#######.....#............#######.....#............#######.....#.....
.......########.................########.................########.................########.................########..........
####################.....####################.....####################.....####################.....####################.....
.####################.....####################.....####################.....####################.....####################....
..####################.....####################.....####################.....####################.....####################...
...####################.....####################.....####################.....####################.....####################..
....####################.....####################.....####################.....####################.....####################.
.....####################.....####################.....####################.....####################.....####################
#.....##############.#####.....##############.#####.....##############.#####.....##############.#####.....##############.####
##.....#############..#####.....#############..#####.....#############..#####.....#############..#####.....#############..###
###....#############...#####....#############...#####....#############...#####....#############...#####....#############...##
####...#############....#####...#############....#####...#############....#####...#############....#####...#############....#
#####..#############.....#####..#############.....#####..#############.....#####..#############.....#####..#############.....
.#####.#############......#####.#############......#####.#############......#####.#############......#####.#############.....
..##################.......##################.......##################.......##################.......##################.....
........#####....................#####....................#####....................#####....................#####............
.........#####....................#####....................#####....................#####....................#####...........
..........#####....................#####....................#####....................#####....................#####..........
...........#####....................#####....................#####....................#####....................#####.........
............#####....................#####....................#####....................#####....................#####........

```
* The width argument must come first. Any reasonable input format (e.g. `w,h`, `w h`, `(w, h)`) is fine.
* Print or return the result with an optional trailing newline.
* You may use any two distinct printable ASCII characters in place of `.` and `#`.
* You can translate the base cell vertically or horizontally, as if it had periodic boundary conditions. Thus the top left corner of the output will not necessarily be a 7×8 rectangle of `.`'s. (**New rule!**)

**The shortest code in bytes wins.**

As a bonus, generate an image instead where each `.` is a pixel of one color and each `#` is a pixel of another color.

# Answer
# Pyth, ~~61~~ ~~60~~ ~~55~~ 49 bytes

```
j*vwmjk*Qd++Rm012Jmms}k++Rhd5U-d4T=T13+Lm1T_mP_dJ

```

Try it online: Demonstration

edit 1: Combine the two statements generating the band and the triangle (see below)

edit 2: Didn't saw that we can use any symbols. Saved 5 bytes edit

edit 3: @Calvin'sHobbies allowed translating the base image. Since my approach was based on this idea, this helped quite a lot. -6 bytes

And for the **Cookie bonus**:

```
.w*vw*RQ++Rm012Jmm*K255}k++Rhd5U-d4T=T13+LmKT_mP_dJ

```

This is only 2 bytes longer (51 bytes) and generates the file `o.png`. For the input `5\n4` it generates the following picture:

## Explanation:

The Houndstooth Pattern looks really quite irregular. But if we bring the left 7 columns to the right and the top 5 rows to the botton we get a much nicer pattern:

```
.#####...................
..#####..................
...#####.................
....#####................
.....#####...............
#.....#####..............
##.....#####.............
###.....#####............
####.....####............
#####.....###............
######.....##............
#######.....#............
########.................
#############.....#######
##############.....######
###############.....#####
################.....####
#################.....###
##################.....##
#############.#####.....#
#############..#####.....
#############...#####....
#############....#####...
#############.....#####..
#############......#####.
#############.......#####

```

First I produce the top-left 13x13 block:

```
.#####.......
..#####......
...#####.....
....#####....
.....#####...
#.....#####..
##.....#####.
###.....#####
####.....####
#####.....###
######.....##
#######.....#
########.....

```

There are 2 simple inequalities, that describe the two `#`-areas. The band can be described by `y + 1 <= x <= y + 5` and the triangle can be described by `x <= y - 5`. I\`ve combined these two conditions:

```
Jmms}k++Rhd5U-d4T=T13
                 =T13   T = 13
 m               T      map each d of [0, 1, ..., 12] to:
                           the list produced by
  m             T          map each k of [0, 1, ..., 12] to:
       +Rhd5                  the list [d+1, d+2, ..., d+5]
      +                       extended by
            U-d4              the list [0, 1, ..., d - 5]
    }k                        test if k is in the list
   s                          and convert the boolean result to 1 or 0
J                       assign this 13x13 block to J

```

Then `+Rm012` adds 12 zeros at the end of each row , to get the upper 25x13 block.

The lower 25x13 block is now really simple:

```
+Lm1T_mP_dJ
      m   J    map each row d of J to:
       P_d        reverse the row and pop the last element
     _         reverse the order the rows
+Lm1T          add T ones at the beginning of each row.

```

All now left is to repeating the pattern and print it

```
j*vwmjk*Qd+upperlower   implicit: Q = first input number
          +upperlower   combine the two blocks to a 25x26 block
    m                   map each row d to:
       *Qd                 repeat d Q times
     jk                    and join to a string
 *vw                    read another number from input and repeat
j                       join by newlines and print

```

The difference to the **Cookie bonus** code:

* `255` instead of `1`
* instead of `mjk*Qd` I use `*RQ`, since I don't want a string
* `.w` saves this 2D-array to file (converts it to png implicitly)
> 17 votes

# Answer
# CJam, ~~106~~ ~~73~~ 71 bytes

```
0000000: 71 7e 22 04 94 51 af 40 6e 73 b2 68 3a e1 7e 13 f2 a1  q~"..Q.@ns.h:.~...
0000012: 3e 1d de f5 64 9c 6b 0f 27 4c 36 d7 81 3d 30 35 56 f8  >...d.k.'L6..=05V.
0000024: cd e8 cd 7c dc 90 31 59 40 8b 8c 22 32 35 36 62 32 32  ...|..1Y@.."256b22
0000036: 62 41 73 33 39 2a 2e 2a 73 32 35 2f 2a 66 2a 4e 2a     bAs39*.*s25/*f*N*

```

Prints `1` and `0` instead of `.` and `#`. Try it online in the CJam interpreter.

### How it works

```
q~      e# Read and evaluate all input. This pushes W and H.
"…"     e# Push an encoding of run lengths of the characters in the output.
256b22b e# Convert from base 256 to base 22.
As39*   e# Push "10" and repeat it 39 times.
.*      e# Vectorized character repetition; multiply each base 22 digit (run
        e# length) by the corresponding character of "10…10".
s25/    e# Flatten and split into chunks of length 25.
*       e# Repeat the resulting array of rows H times.
f*      e# Repeat each row W times.
N*      e# Join the rows, separating by linefeeds.

```

### Cookie bonus

```
0000000: 27 50 6f 31 70 71 7e 5d 5f 5b 32 35 5f 29 5d 2e 2a 5c  'Po1pq~]_[25_)].*\
0000012: 7e 22 04 94 51 af 40 6e 73 b2 68 3a e1 7e 13 f2 a1 3e  ~"..Q.@ns.h:.~...>
0000024: 1d de f5 64 9c 6b 0f 27 4c 36 d7 81 3d 30 35 56 f8 cd  ...d.k.'L6..=05V..
0000036: e8 cd 7c dc 90 31 59 40 8b 8c 22 32 35 36 62 32 32 62  ..|..1Y@.."256b22b
0000048: 41 73 33 39 2a 2e 2a 73 32 35 2f 2a 66 2a 73 2b 4e 2a  As39*.*s25/*f*s+N*

```

prints a Portable BitMap instead of ASCII art.

Below is the output for input `24 13`, converted to PNG:
> 11 votes

# Answer
# Befunge-93, ~~2120~~ 1967 bytes

Here's some high quality befunge, with exception-handling for debugging!

```
&&00p10pv
v       <
    >94+2*20p        v
>00g|   >                v
    @                >10g>0020gv-1:<
                               >:0`|
                     ,       v    $<
                     +        >v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v
 v_$1-:#^_$20g1-20p55^       >|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>"!DAB"....@
 ,:
 >^".......#.....#####......."                                                    <
  ^".......##.....#####......"                                                  <
  ^".......###.....#####....."                                                <
  ^".......####.....####....."                                              <
  ^".......#####.....###....."                                            <
  ^".......######.....##....."                                          <
  ^".......#######.....#....."                                        <
  ^".......########.........."                                      <
  ^"####################....."                                    <
  ^".####################...."                                  <
  ^"..####################..."                                <
  ^"...####################.."                              <
  ^"....####################."                            <
  ^".....####################"                          <
  ^"#.....##############.####"                        <
  ^"##.....#############..###"                      <
  ^"###....#############...##"                    <
  ^"####...#############....#"                  <
  ^"#####..#############....."                <
  ^".#####.#############....."              <
  ^"..##################....."            <
  ^"........#####............"          <
  ^".........#####..........."        <
  ^"..........#####.........."      <
  ^"...........#####........."    <
  ^"............#####........"  <
^                     p00-1g00<

```

(Obviously, this is still very golfable. I just wanted to get an answer up here for now)

So, this is made up of different parts.

```
&&00p10p

```

This is just the initializer, it takes in the values and stores them

```
    >94+2*20p
>00g|      >
    @

```

This section resets the row count, so we can print out another (width) pictures side by side. `94+2*` is calculating 26, the number of rows. Also, if the height is zero, the program will terminate.

```
>10g

```

This gets the width on the stack so we know how many to print

```
0020gv-1:<
     >:0`|
         $

```

This adds two dummy values to the stack to tell when we've finished an operation, as well as what row (n) we're on. This then adds n values to the stack

```
>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v
|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>|>"!DAB"....@

                                                    <
                                                  <
                                                <
                                              <
                                            <
                                          <
                                        <
                                      <
                                    <
                                  <
                                <
                              <
                            <
                          <
                        <
                      <
                    <
                  <
                <
              <
            <
          <
        <
      <
    <
  <
<

```

This is a control section that will to the (26-n) row. This is the easiest way i could figure out how to do it.

```
".......#.....#####......."
".......##.....#####......"
".......###.....#####....."
".......####.....####....."
".......#####.....###....."
".......######.....##....."
".......#######.....#....."
".......########.........."
"####################....."
".####################...."
"..####################..."
"...####################.."
"....####################."
".....####################"
"#.....##############.####"
"##.....#############..###"
"###....#############...##"
"####...#############....#"
"#####..#############....."
".#####.#############....."
"..##################....."
"........#####............"
".........#####..........."
"..........#####.........."
"...........#####........."
"............#####........"

```

This, obviously, is read and will pop whatever row is read onto the stack backwards. This means when we pop it off, it will print properly.

```
v_
,:
>^

```

This will print until the stack hits a 0, which we left on earlier.

```
1-:#^_

```

This takes 1 off of the number of the specific line to print, then checks if it's zero or not. If it's non-zero, we go back to the fourth block of code.

```
          ,
          +
20g1-20p55^

```

This subtracts 1 from the row (n), prints a newline, and goes back to block 3

```
p00-1g00

```

Once of all of the rows have printed, this subtracts one from the initial height and goes back to block 2.

All the rest of the code is either control flow or stack management. Writing this mas more than I thought it would be, but I'm satisfied with how it looks. It's much more golfable, and that will likely remain a project for another day.

**2120 -\> 1967**: trimmed up some lines with a lot of wasted spaces
> 7 votes

# Answer
# Perl, 243

(One byte added for the `-n` switch to fetch input from stdin.)

```
($w,$h)=split;for(1..$h){print((sprintf("%025b",hex)x$w).$/)foreach qw(20f80 307c0 383e0 3c1e0 3e0e0 3f060 3f820 3fc00 1ffffe0 fffff0 7ffff8 3ffffc 1ffffe fffff 107ffef 183ffe7 1c3ffe3 1e3ffe1 1f3ffe0 fbffe0 7fffe0 1f000 f800 7c00 3e00 1f00)}

```

This is fairly straightforward — all it does is convert an array of 26 hex numbers to binary and print them out the required number of times.

### Example:

Input:

```
3 2

```

Output:

```
000000010000011111000000000000001000001111100000000000000100000111110000000
000000011000001111100000000000001100000111110000000000000110000011111000000
000000011100000111110000000000001110000011111000000000000111000001111100000
000000011110000011110000000000001111000001111000000000000111100000111100000
000000011111000001110000000000001111100000111000000000000111110000011100000
000000011111100000110000000000001111110000011000000000000111111000001100000
000000011111110000010000000000001111111000001000000000000111111100000100000
000000011111111000000000000000001111111100000000000000000111111110000000000
111111111111111111110000011111111111111111111000001111111111111111111100000
011111111111111111111000001111111111111111111100000111111111111111111110000
001111111111111111111100000111111111111111111110000011111111111111111111000
000111111111111111111110000011111111111111111111000001111111111111111111100
000011111111111111111111000001111111111111111111100000111111111111111111110
000001111111111111111111100000111111111111111111110000011111111111111111111
100000111111111111110111110000011111111111111011111000001111111111111101111
110000011111111111110011111000001111111111111001111100000111111111111100111
111000011111111111110001111100001111111111111000111110000111111111111100011
111100011111111111110000111110001111111111111000011111000111111111111100001
111110011111111111110000011111001111111111111000001111100111111111111100000
011111011111111111110000001111101111111111111000000111110111111111111100000
001111111111111111110000000111111111111111111000000011111111111111111100000
000000001111100000000000000000000111110000000000000000000011111000000000000
000000000111110000000000000000000011111000000000000000000001111100000000000
000000000011111000000000000000000001111100000000000000000000111110000000000
000000000001111100000000000000000000111110000000000000000000011111000000000
000000000000111110000000000000000000011111000000000000000000001111100000000
000000010000011111000000000000001000001111100000000000000100000111110000000
000000011000001111100000000000001100000111110000000000000110000011111000000
000000011100000111110000000000001110000011111000000000000111000001111100000
000000011110000011110000000000001111000001111000000000000111100000111100000
000000011111000001110000000000001111100000111000000000000111110000011100000
000000011111100000110000000000001111110000011000000000000111111000001100000
000000011111110000010000000000001111111000001000000000000111111100000100000
000000011111111000000000000000001111111100000000000000000111111110000000000
111111111111111111110000011111111111111111111000001111111111111111111100000
011111111111111111111000001111111111111111111100000111111111111111111110000
001111111111111111111100000111111111111111111110000011111111111111111111000
000111111111111111111110000011111111111111111111000001111111111111111111100
000011111111111111111111000001111111111111111111100000111111111111111111110
000001111111111111111111100000111111111111111111110000011111111111111111111
100000111111111111110111110000011111111111111011111000001111111111111101111
110000011111111111110011111000001111111111111001111100000111111111111100111
111000011111111111110001111100001111111111111000111110000111111111111100011
111100011111111111110000111110001111111111111000011111000111111111111100001
111110011111111111110000011111001111111111111000001111100111111111111100000
011111011111111111110000001111101111111111111000000111110111111111111100000
001111111111111111110000000111111111111111111000000011111111111111111100000
000000001111100000000000000000000111110000000000000000000011111000000000000
000000000111110000000000000000000011111000000000000000000001111100000000000
000000000011111000000000000000000001111100000000000000000000111110000000000
000000000001111100000000000000000000111110000000000000000000011111000000000
000000000000111110000000000000000000011111000000000000000000001111100000000

```
> 6 votes

# Answer
# Rev 1, C, ~~118~~ 115 bytes

```
i,x,y;f(w,h){for(i=26*h*(w*=25);i--;i%w||puts(""))x=i%25,y=i/w%26,putchar(((y>x^y>x+5^x>y+4)&y/13==x/13^y/13)+34);}

```

9 bytes saved due to new rule allowing translation of the cell. 3 bytes saved by use of `w*=25`. Rest of post remains unchanged.

# Rev 0, C, 127 bytes

```
i,x,y;f(w,h){for(i=650*w*h;i--;i%(25*w)||puts(""))x=(i+20)%25,y=(i/25/w+8)%26,putchar(((y>x^y>x+5^x>y+4)&y/13==x/13^y/13)+34);}

```

This goes through the characters, printing them one by one. `i%(25*w)||puts("")` inserts a newline at the end of each line.

My way of viewing the design is similar to Jakube's, but I bring the top 8 rows to the bottom and the 5 right columns to the left to get the following view. In the program this step is "reversed" by `+20` and `+8` in the expressions for x and y.

```
"""""####################
#"""""###################
##"""""##################
###"""""#################
####"""""################
#####"""""###############
"#####"""""##############
""#####"""""#############
"""#####""""#############
""""#####"""#############
"""""#####""#############
""""""#####"#############
"""""""##################
"""""""""""""#####"""""""
""""""""""""""#####""""""
"""""""""""""""#####"""""
""""""""""""""""#####""""
"""""""""""""""""#####"""
""""""""""""#"""""#####""
""""""""""""##"""""#####"
""""""""""""###"""""#####
""""""""""""####"""""####
""""""""""""#####"""""###
""""""""""""######"""""##
""""""""""""#######"""""#
""""""""""""########"""""

```

Apart from the "inversion of colours" it may look very similar, but there is an important difference: the diagonal stripes match up. (note that the original design does not have diagonal symmetry as it measures 25x26.)

The expression `((y>x^y>x+5^x>y+4)^y/13)+34` produces the following, where the various comparison operators produce the stripes, the `^y/13` produces the "colour flip" half way up and the `+34` takes the resulting number `0,1` and boosts it to the ASCII range `34,35`.

```
"""""####################
#"""""###################
##"""""##################
###"""""#################
####"""""################
#####"""""###############
"#####"""""##############
""#####"""""#############
"""#####"""""############
""""#####"""""###########
"""""#####"""""##########
""""""#####"""""#########
"""""""#####"""""########
########"""""#####"""""""
#########"""""#####""""""
##########"""""#####"""""
###########"""""#####""""
############"""""#####"""
#############"""""#####""
##############"""""#####"
###############"""""#####
################"""""####
#################"""""###
##################"""""##
###################"""""#
####################"""""

```

The term `&y/13==x/13` evaluates to false=0 in the top right and bottom left quarters, producing the square part of the pattern as shown previously. Note that because the program downcounts, the origin x=y=0 is at bottom right. This is handy as the square of `#` is 13 characters wide while the square of `"` is only 12 characters wide.
> 3 votes

# Answer
# Befunge-93, 968 bytes

Yes, that's right! A competing Befunge answer!

```
&:&\00p10p:520pv:g00p02<v  <
    #   p1*45-1_v#:" "  <  v
    |`-1*65:g02$<      ,
    >:" "\39*\p:" "\47 *v
+:"<"\39*\p:"v"\47*\p25^>\p 1
".......#.....#####......."<v
".......##.....#####......"
".......###.....#####....."
".......####.....####....."
".......#####.....###....."
".......######.....##....."
".......#######.....#....."
".......########.........."
"####################....."
".####################...."
"..####################..."
"...####################.."
"....####################."
".....####################"
"#.....##############.####"
"##.....#############..###"
"###....#############...##"
"####...#############....#"
"#####..#############....."
".#####.#############....."
"..##################....."
"........#####............"
".........#####..........."
"..........#####.........."
"...........#####........."
"............#####........"
,,,,,,,,,,,,,,,,,,,,,,,,,  v>
    > 10g1-:10p #v_@
 " " \47*\p5:"<"v>:" "\39*\ p
\*74 \"v":p\*93\<      v,*5 2p

```

Explanation tomorrow, bed now. I will say, however, that I do clever stuff with moving a couple redirection arrows and I use the wrap-around property quite a bit too. Test it out in this online interpreter.
> 2 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Palandrome-ish code

text:
# Question
Title: Palandrome-ish code
Create a program that does the same thing forwards and backwards, in **different languages**. “Different languages” does not include different versions of the same language.

## Challenge

This program can take any input and write anything to stdout and stderr. However, the program must output *exactly the same* things for the same input when run backwards in the other language. This explicitly includes anything written to stderr **while the program is running**, including errors. The length of the output from stdout and stderr must sum to at least 5. The minimum program length is 2 bytes.

* This is a , so the answer with the most votes wins.
* Comments are allowed, however the commented text must take up less than ¼ of the total program.

# Answer
> 4 votes
# BF + Foo

You saw it coming

```
-[------->+<]>-.-[->+++++<]>++.+++++++..+++."olleH"

```

---
Tags: popularity-contest, polyglot
---


title: How did the chicken cross the road?

text:
# Question
Title: How did the chicken cross the road?
Cluck cluck. No one knows why the chicken crossed the road, maybe there was a good looking rooster on the other side. But we can figure out how. Write a program, that, left to right, crosses this (or any) "road".

```
1356 | 1738
3822 | 1424
3527   3718
9809 | 5926
0261 | 1947
7188   4717
6624 | 9836
4055 | 9164
2636   4927
5926 | 1964
3144 | 8254

```

Your program "crosses" it, moving left to right. You start on any number on the leftmost column you like. From there, you can move to any adjacent character to the right. If you started at the top left corner, 1, you could go to either 3 or 8. Every number you go to, including the starting number, is added to a sum. Spaces do not add to your sum. "|" forces you to move up or down, rather than somewhere to the right. (You CAN'T move forward on this character) Your goal is to get to the other side with the smallest possible sum. Your program must print out the sum at the end, and it must be able to solve any road. Preferably, it could also have input for a road, but it's not required. Your program must print both the path and the sum. Fewest bytes of code wins.

To clarify, you can move diagnally unless you are on a vertical bar. You can only move up and down when you are on a vertical bar.

For a clearer specification of roads, it is basically a string of text (Or an array of columns or rows, should you prefer to think that way) that follows the rules of the characters, and there can't be anything BUT those characters in the road. There can be any number, a space, a bar ("|"), or a newline. If a road was paved by a drunk guy, as in ProgrammerDan's answer, it is still a valid road, and your program must be able to solve such a road. It is not considered a road if it is impossible to get to the other side (For example, there is no way out of a straight line of bars).

Your program is not required to determine if a road is invalid.

Key:
Any number - adds the number to your sum, move forward.
Space - Move forward, nothing is added to your sum.
"|" - Move up or down, nothing is added to your sum.

EDIT: An example solution, as suggested. I can't make a horribly big one, I can't get on an IDE to solve it for me ATM.

Take this small road:

```
9191 | 8282
1919 | 2727
5555   5555

```

The solution would be a path of 1, 1, 1, 1, space, divider, divider, space, space, 2, 2, 2, 2 for a total of 12.

EDIT #2: The solution to the first road on this question, as determined by Geobits and peoples programs, is 0,2,0,1, , , ,1,4,1,4 for a sum of 13.

# Answer
> 3 votes
# Pyth, ~~168~~ ~~143~~ 141 bytes \[now Drunken Road compatible\]

~~My test case works, but because of a misunderstanding on my part, it won't work properly with the initial example. I'm working on fixing it.~~

Now working for original example and drunken roads

Some ~~REALLY~~ ~~slightly less ugly~~ code:

```
=Z.dC,++\ `MUT\|++0UT=^T5Ltu+G]?&qeeG\|<heGhH+eGeHHtb,0hbKhohNum++hed@ZhhdtedC,H_y_y.b+N]YmhohNd.:++TGT3HCm.[d\ lh.MlZ.z.z*hl.z]]0j\,t.sK\ hK

```

Test it Here

I tested it on a 10+9 x 40 road.

```
6417443208|153287613
8540978161|726772300
7294922506 263609552
0341937695 498453099
9417989188 370992778
2952186385|750207767
7049868670 756968872
1961508589|379453595
0670474005 070712970
4817414691|670379248
0297779413|980515509
6637598208 090265179
6872950638 767270459
7375626432 439957105
1387683792|544956696
6974831376 545603884
0949220671|632555651
3952970630|379291361
0456363431|275612955
2973230054|830527885
5328382365|989887310
4034587060 614168216
4487052014|969272974
5015479667 744253705
5756698090|621187161
9444814561|169429694
7697999461|477558331
3822442188 206942845
2787118311|141642208
2669534759 308252645
6121516963|554616321
5509428225|681372307
6619817314|310054531
1759758306 453053985
9356970729|868811209
4208830142 806643228
0898841529|102183632
9692682718|103744380
5839709581|790845206
7264919369|982096148

```

# Answer
> 4 votes
# Java, 955 bytes

Obviously not going to win any awards, being Java and all, but I love this problem and wanted to throw in my own entry.

Features and limits:

* Can support irregular roads (super drunk!) including variable widths, complex lines, etc.
* Expects road to be input as parameters on execution; the ungolfed version also supports reading from stdin, but since input method wasn't specified the golfed version expects smallest!
* Uses some dynamic programming technique I haven't used in, oh, 6 years or so to efficiently solve in O(n\*m) time, where n is rows and m is columns.
    + Solves from right to left, marking the best direction to take *from* the current index to the next index.
    + "lines" are handled by resolving their column, then addressing them if reachable on the next column over. They resolve by storing direction up or down, with the cost of the eventually reachable non-line.
* Tracks, but doesn't print (in golf'd version) the *starting index* of the best solution.

Ok, enough jibba jabba. Golfed version:

```
class C{public static void main(String[]a){int n=a.length,m=0,i=0,j=0,h=0,p=0,q=0,s=0,t=0,b=-1,c=2147483647,x=0,y=0;char[][]r=new char[n][];char u;for(String k:a){j=k.length();m=(j>m)?j:m;}for(String k:a)r[i++]=java.util.Arrays.copyOf(k.toCharArray(),m);int[][][]d=new int[n][m][2];for(j=m-1;j>=0;j--){for(i=0;i<n;i++){u=r[i][j];p=(u=='\0'||u==' '||u=='|'?0:u-'0');if(j==m-1)d[i][j][1]=p;else{if(u=='|')d[i][j][0]=-1;else{for(h=-1;h<2;h++){x=i+h;y=j+1;if(x>=0&&x<n){if(d[x][y][0]==-1){s=x-1;while(s>=0&&r[s][y]=='|')s--;t=x+1;while(t<n&&r[t][y]=='|')t++;if((s>=0&&t<n&&d[s][y][1]<d[t][y][1])||(s>=0&&t>=n)){t=d[s][y][1];s=4;}else{s=6;t=d[t][y][1];}d[x][y][0]=s;d[x][y][1]=t;}q=d[x][y][1]+p;if(d[i][j][0]==0||q<d[i][j][1]){d[i][j][0]=h+2;d[i][j][1]=q;}}}}}if(j==0&&(b<0||d[i][j][1]<c)){b=i;c=d[i][j][1];}}}String o="";i=b;j=0;while(j<m){u=r[i][j];if(u=='\0')j=m;else{o+=u+",";h=d[i][j][0]-2;if(h>1)i+=h-3;else{i+=h;j++;}}}System.out.println(o+"\b:"+c);}}

```

As per my habit, github with the ungolfed code.

Solution for "first" road:

```
$ java C "1356 | 1738" "3822 | 1424" "3527   3718" "9809 | 5926" "0261 | 1947" "7188   4717" "6624 | 9836" "4055 | 9164" "2636   4927" "5926 | 1964" "3144 | 8254"
0,2,0,1, , , ,1,4,1,4:13

```

Second example:

```
$ java C "9191 | 8282" "1919 | 2727" "5555   5555"
1,1,1,1, ,|,|, , ,2,2,2,2:12

```

Brian Tuck's sample:

```
$ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956696" "6974831376 545603884" "0949220671|632555651" "3952970630|379291361" "0456363431|275612955" "2973230054|830527885" "5328382365|989887310" "4034587060 614168216" "4487052014|969272974" "5015479667 744253705" "5756698090|621187161" "9444814561|169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148"
2,1,0,1,5,1,2,1,1,1, ,1,0,1,2,1,2,3,0,1:26

```

"Drunkified" Brian's example:

```
6417443208|153287613
8540978161|726772300
7294922506 263609552
0341937695 498453099
9417989188 370992778
2952186385|750207767
7049868670 756968872
1961508589|379453595
0670474005 070712970
4817414691|670379248
0297779413|980515509
6637598208 090265179
6872950638 767270459
7375626432 439957105
1387683792|544956
697483176 5456034
09492201|6325551
395297030|3792913
 456363431|275612
  73230054|830527885
    8382365|989887310
    4587060 614168216
  87052014|96927297
 50479667 7442537
57566980 | 621187161
944481456 | 169429694
7697999461|477558331
3822442188 206942845
2787118311|141642208
2669534759 308252645
6121516963|554616321
5509428225|681372307
6619817314|310054531
1759758306 453053985
9356970729|868811209
4208830142 806643228
0898841529|102183632
9692682718|103744380
5839709581|790845206
7264919369|982096148

```

```
$ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956" "697483176 5456034" "09492201|6325551" "395297030|3792913" " 456363431|275612" "  73230054|830527885" "    8382365|989887310" "    4587060 614168216" "  87052014|96927297" " 50479667 7442537" "57566980 | 621187161" "944481456 | 169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148"
 , , , ,0,5,2,0,1, , , ,1,1,1,3,2:16

```

Solution visualized:

```
09492201|6325551
395297030|3792913
\456363431|275612
 \73230054|830527885
  \ 8382365|989887310
   \4\87060 614168216
  87/5--\4|96927\97
 50479667\74425/7
57566980 |\62-/87161
944481456 |\/69429694
7697999461|477558331

```

Enjoy!

Edit: Now I'm just showing off (two roadways merge! Can he make it?)

```
948384 | 4288324   324324 | 121323
120390 | 1232133   598732 | 123844
 293009 | 2394023 432099 | 230943
 234882 | 2340909 843893 | 849728
  238984 | 328498984328 | 230949
  509093 | 904389823787 | 439898
   438989 | 3489889344 | 438984
   989789 | 7568945968 | 989455
    568956 | 56985869 | 568956
    988596 | 98569887 | 769865
     769879 | 769078 | 678977
     679856 | 568967 | 658957
      988798 | 8776 | 987979
      987878 | 9899 | 989899
       999889 |    | 989899
       989999 |    | 989999
        989898 |  | 998999
        989999 |  | 999999
         989998 || 899999
         989998 || 998999

```

Solution:

```
$ java C "948384 | 4288324   324324 | 121323" "120390 | 1232133   598732 | 123844" " 293009 | 2394023 432099 | 230943" " 234882 | 2340909 843893 | 849728" "  238984 | 328498984328 | 230949" "  509093 | 904389823787 | 439898" "   438989 | 3489889344 | 438984" "   989789 | 7568945968 | 989455" "    568956 | 56985869 | 568956" "    988596 | 98569887 | 769865" "     769879 | 769078 | 678977" "     679856 | 568967 | 658957" "      988798 | 8776 | 987979" "      987878 | 9899 | 989899" "       999889 |    | 989899" "       989999 |    | 989999" "        989898 |  | 998999" "        989999 |  | 999999" "         989998 || 899999" "         989998 || 998999"
 ,2,0,3,0,0, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, , , , , , , ,|, ,|, ,|, ,|, ,|, ,|, ,|,|, , ,1,0,7,2:15

```

(bonus: path from ungolfed):

```
$ java Chicken < test5.txt
best start: 3 cost: 15
  -> 2 -> 0 -> 3 -> 0 -> 0 ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->
  -> | -> | ->   ->   ->   ->   ->   ->   ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | -> | ->
  ->   -> 1 -> 0 -> 7 -> 2 -> 15
/ -> - -> - -> \ -> / -> / -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , ->
- -> , -> , -> / -> \ -> - -> - -> - -> / -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> , -> , ->
/ -> - -> \ -> \ -> - -> \ -> across

```

## Details on Algorithm

A more complete explanation of the Dynamic Programming technique I employed was requested, so here goes:

I'm using a mark-and-precompute method of solution. It has a proper name, but I've long since forgotten it; perhaps someone else can offer it?

### Algorithm:

* Starting at the right-most column and progressing to the left, compute the following about each cell in the column:
    + The summation of lowest cost movement, defined as *current cell cost* \+ *lowest cost cell reachable in the next column*
    + The movement action to take to achieve this lowest cost, as simply a valid move from this cell to another single cell.
* Pipes are deferred. To resolve a pipe, you need to have the full column computed, so we don't compute pipes until the next column.
    + When determining the lowest cost of a cell to the left of a pipe, we first compute the best direction to travel along the pipe -- it will always resolve to either up, or down, so we compute it once.
    + We then store, as with all other cells, the best cost (defined as the cost of the cell we reach by travelling either up or down on the pipe) and the direction to travel to reach it.

### Notes:

That's it. We scan from top to bottom, right to left, once; the only cells touched (potentially) more then once are pipes, however, each pipe is only "solved" once, keeping us within our O(m\*n) window.

To handle "odd" map sizes, I chose to simply pre-scan and normalize lengths of rows by padding with null characters. Null characters count as "zero cost" moves same as pipes and spaces. Then, in printing the solution, I stop printing costs or moves when either the edge of the normalized road is reached, or a null character is reached.

The beauty of this algorithm is it's very simple, applies the same rules to every cell, producing a full solution by solving O(m\*n) sub-problems, and in terms of speed is rather fast. It does trade off memory, creating effectively two copies in memory of the roadway map, the first to store "best cost" data and the second to store "best move" data per cell; this is typical for dynamic programming.

---
Tags: code-golf, path-finding
---


title: A Perplexing Puzzle

text:
# Question
Title: A Perplexing Puzzle
# The Challenge

Create a program or function that takes no input, and outputs (or returns):

```
I'm a programming paradox — no I'm not.

```

Without using a character twice in any string, or digit twice in any integer.

---

# Rules

1. You may not use any character twice *within a string*. For example, the word `"test"` would violate this rule.
2. You may not use any character twice *between strings*. For example, if somewhere in your code you have the string `"hi"`, no other strings may contain the substring `"h"` or `"i"`.
3. You may not use a digits more than once *within an integer*. For example, the integer `200` would not be acceptable.
4. You may not use a digit more than once *between integers*. For example, if you have the integer `40` in your code, you may not have the integer `304`.
5. The above rules do not apply between data types. You could, for example, have the string `"9"` and the integer `9` in your code.
6. An uppercase letter is considered a separate character from the lowercase.
7. You may only use printable ASCII characters in your strings.
8. You may not set variables to each character and add them together.

---

# Example

Here is an example, written in Python 2, of what the same challenge might look like with the string "Hello, World!" instead.

```
print"He"+"l"*2+"o, "+"W"+chr(int("1"*3))+"r"+chr(108)+"d!"

```

---

Note: For those wondering why I chose this particular string; I chose it because it has several repeated characters and a repeated word. It has no greater significance or meaning.

# Answer
> 2 votes
# Javascript (ES6), ~~89~~ ~~86~~ 84 Bytes

```
`${y=>I0m3a3programming3paradox313no3I0m3not2}`.slice(3).replace(/\d/g,m=>"'—. "[m])

```

# Answer
> 11 votes
# Python 2, ~~186~~ ~~155~~ ~~139~~ ~~138~~ ~~126~~ ~~109~~ 98 bytes

I don't know if this is a loophole...

```
OKDLPLGHFBHPDDCEBLGPHPAFJLMLEFLOKDLEFIN=0
print list(locals())[3].translate("adgimnoprtx' -.I"*16)

```

~~don't think~~ I can golf more than this...

# Answer
> 4 votes
# Javascript (ES6), ~~142~~ ~~105~~ ~~98~~ 96 bytes

```
[a="I'm","a",`${y=>programming}`.slice(3),`${no=>paradox}`.slice(4),'-',x="no",a,x+"t."].join` `

```

Another possible rule-breaker, but it was fun, anyway. :)

Original version:

```
[a="I'm",(''+(b=>a)).substr(3),(''+(is=>programming)).substr(4),(''+(Fermi=>paradox)).substr(7),'-',(''+(yes=>no)).substr(5),a,'not.'].join` `

```

# Answer
> 4 votes
## C++14, 327 bytes

```
#include <iostream>
#define x(y) <<(y)[s]
std::string s[]={"I'"," ","a","p","r","o","g","m","n","i","d","x","—","t","."};enum{J,S,A,P,R,O,G,M,N,I,D,X,W,T,Z};[]{std::cout x(J)x(M)x(S)x(A)x(S)x(P)x(R)x(O)x(G)x(R)x(A)x(M)x(M)x(I)x(N)x(G)x(S)x(P)x(A)x(R)x(A)x(D)x(O)x(X)x(S)x(W)x(S)x(N)x(O)x(S)x(J)x(M)x(S)x(N)x(O)x(T)x(Z);}();

```

I'm defining a macro which returns a string to the `<<` operator, mapping the necessary characters in a string array and access them with an `enum`

# Answer
> 1 votes
# Haskell, 320 bytes

```
import Data.Char

data Letter = A|D|I|I'm|MM|P|R|G|N|O|X|Y|S|T deriving Show

transform :: Letter -> String
transform S = " "
transform Y = "—"
transform I'm = "I'm"
transform x = map toLower $ show x

main :: IO ()
main = print $ transform =<<
   [I'm,S,A,S,P,R,O,G,R,A,MM,I,N,G,S,P,A,R,A,D,O,X,S,Y,S,N,O,S,I'm,S,N,O,T]

```

---
Tags: code-golf, restricted-source
---


title: Right-align text

text:
# Question
Title: Right-align text
Your job is to take a string input and a number and align the string to the right, making the width of the text the number. When a line is too long, break it and put the rest on the next line, repeating until it's not necessary. If a line is shorter than the width, then pad it with spaces. Multiple newlines can occur, and should be treated like any other single character.

For example, the string

```
Programming
Puzzles
&
Code
Golf

```

and the number `5` would produce:

```
Progr
ammin
    g
Puzzl
   es
    &
 Code
 Golf

```

Whereas the same string and the number `10` would produce:

```
Programmin
         g
   Puzzles
         &
      Code
      Golf

```

The string

```
a

b

```

and the number 5 would produce:

```
    a
      <-- note the 5 spaces
    b

```

Shortest code wins!

# Answer
# Pyth, 14 bytes

```
jm.[\ QdscRQ.z

```

Demonstration

Uses Pyth's pad operator.
> 8 votes

# Answer
## Python 2, 84

```
s,n=input()
for w in s.split('\n'):
 w=w or' '
 while w:print w[:n].rjust(n);w=w[n:]

```

Takes as input a string with newlines and a number, and prints the result. For each line in the input, takes and prints `n` chars at a time, using the built-in `rjust` to pad the left with spaces before printing.

I fixed the empty line case with the hack `w=w or' '`. There's probably a better method but I'm not going to think much about it.
> 10 votes

# Answer
# CJam, 21 bytes

```
li_qN/Sfe|f/ff{\Se[N}

```

*Thanks to @Sp3000 for golfing off 1 byte and paving the way for 3 more.*

Try it online in the CJam interpreter.

### How it works

```
li                     Read an integer L from the first line of input.
  _                    Push a copy.
   qN/                 Split the remaining input at linefeeds.
      Sfe|             Map `OR " "'; the replaces empty lines with a space.
          f/           Split each line into chunks of length L.
            ff{     }  For each chunk, push L and the chunk; then:
               \         Swap L with the chunk.
                Se[      Left-pad the chunk to length L by prepending " ".
                   N     Push a linefeed.

```
> 8 votes

# Answer
# Pyth, 16

```
jm>Q+*\ QdscRQ.z

```

Try it online here

### Explanation

```
jm>Q+*\ QdscRQ.z             : Q is the number on the first line, .z takes the rest
           cRQ.z             : chop each line of .z into chunks of Q characters
 m        s                  : remove nested lists and map over the result
    +*\ Qd                   : add Q spaces to each line d
  >Q                         : take the last Q characters of that result
j                            : join results on newlines

```
> 5 votes

# Answer
# Perl, 39 bytes

```
perl -ni5 -e 's!^$|.{1,$^I}!printf"%${^I}s
",$&!ge'

```

36 bytes + 3 bytes for `-ni`. The wrap width is passed as the argument to `-i`.

Handles blank lines properly by padding them with spaces:

```
$ echo -e "Programming\nPuzzles\n\n&\n\nCode\nGolf" | perl -ni5 -e 's!^$|.{1,$^I}!printf"%${^I}s
",$&!ge'
Progr
ammin
    g
Puzzl
   es

    &

 Code
 Golf

```

## How it works

This solution uses the substitution operator to loop through the input, saving a byte over the equivalent `for` loop. The real trick, though, is in the regex on the LHS of the substitution:

```
^$|.{1,$^I}

```

With the global modifier, this will match `$^I` characters at a time; when there are less than `$^I` characters remaining in the string, it will match everything to the end. The alternation with `^$` is required to handle blank lines. For example:

```
$ echo -e "foo\n\nbar" | perl -ni2 -E 'say "<$_>" for /^$|.{1,$^I}/g'
<fo>
<o>
<>
<ba>
<r>

```

The RHS of the substitution simply uses `printf` to left-pad the matched chunk with spaces.
> 4 votes

# Answer
# Javascript (ES6), 107

I wish JS had a built in pad function. Oh well.

```
(a,b)=>a.replace(eval(`/(.{${b}})(?!\\n)/g`),`$1
`).split`
`.map(c=>(Array(b).join` `+c).slice(-b)).join`
`

```

Explanation:

```
(a, b)=>

  // searches for sequences of characters longer than b without a newline after them and
  // adds a newline after every b characters of the sequence
  a.replace(eval(`/(.{${b}})(?!\\n)/g`), '$1\n')
    .split('\n')
    .map(c=>

      // prepends b spaces to each string then slices it from the right down to length b
      ( Array(b).join(' ') + c ).slice(-b)

    ).join('\n')

```
> 3 votes

# Answer
# Julia, 126 bytes

```
f(s,n)=for i=split(s,"\n") while length(i)>0 println(lpad(i[1:min(n,end)],n));length(i)<n?break:(i=i[min(n+1,end):end])end;end

```

Ungolfed:

```
function f(s::String, n::Int)
    for i in split(s, "\n")
        while length(i) > 0
            println(lpad(i[1:min(n,end)], n))
            length(i) < n ? break : (i = i[min(n+1,end):end])
        end
    end
end

```
> 3 votes

# Answer
## Bash, 62, 61+feature, 59

Shorter if `N` can be set by the caller, instead of having to read it as the first line of input.

```
# width as a function arg: 59 chars
f()while read -rn$1 r;do [[ $r ]]&&printf %$1s\\n "$r";done
# width on stdin: 64 chars  (not updated with later suggestions&ideas)
read N;while read -rn$N r;do [[ $r ]]&&printf %$N's\n' "$r";done

```

This fails to handle empty lines in the input. Otherwise, this doesn't subject the input data to word-splitting, pathname expansion, or otherwise treat it as more than just raw data.

`read -n$N` saves one character, but lets `read` munge `\`.

The `[[ $r ]]&&` is needed because `read -n4` can't lookahead to see that the next char is a newline. So it sets `r` to a 4-char string, and the next read produces a zero-char empty string. Filtering these false newlines without filtering real newlines would require tracking state: whether the previous line was max-length or not. Either more code or a totally different approach would be needed.

`[[ $r ]]` is shorter than `[ -n "$r" ]` which is needed to avoid errors if the line starts with `-z foo`, or is `*` or something, if you used `[ $r ]`.

Justication happens with the standard printf "%4s" format string.

Test with

```
f()(while read -rn$1 r;do [[ $r ]]&&printf %$1s\\n "$r";done); (echo 4; echo -e "*\n\\"; cat /tmp/lines) | f 4

```
> 2 votes

# Answer
# Haskell, 108 bytes

```
import Data.List.Split
k[]=[""]
k x=x
f n=unlines.(map(\l->([1..n-length l]>>" ")++l).k.chunksOf n=<<).lines

```

Usage example:

```
*Main> putStr $ f 5 "a\n\nb\ncd\nMatamorphosis"
    a

    b
   cd
Matam
orpho
  sis

```

How it works

```
                              .lines   -- split input string at newlines
                           =<<         -- for every line
                  chunksOf n           --    split into chunks of length n
                k                      --    fix empty lines
    map                                --    for every chunk
        \l->([1..n-length l]>>" "      --      make a string of missing spaces
                        ++l            --      and append the chunk
unlines                                -- join padded chunks with newlines in-between

```
> 2 votes

# Answer
## GNU awk + bash, 70

```
f()(awk -vFPAT=.\{,$1} '{for(i=0;i++<NF;){printf "%'$1's\n",$i}}/^$/')

```

Using bash to slot the count into the awk program is prob. smaller than reading it with a `NR==1{N=$0}` block.

Read a line at a time. Split into at-most-4 character chunks, using FPAT. (matches the fields, rather than the separators. GNU extension.) printf each field separately. (Default ORS = \n).

The `/^$/` rule is there to print empty lines, which have NF=0 and thus don't print at all in the other block. So unlike my pure-bash solution, this actually works in the general case.

Semi-unrelated, but my idea so far for perl is 112 chars for just the perl code:

```
(echo 4; echo -e 'foo\nbar'; echo -e "*\n\\"; echo '~$(true)'; cat /tmp/lines) |  # test input
perl -e '$N=<>;$/=\1;print "$N\n"; while(<>){if(/\n/ or length($l)>=$N){printf("%$4s\n",$l);$l=/\n/?"":$_;}else{$l.=$_;}}'

```

This eats one of the newlines, and is way too long. `$/=\1` reads a byte at a time. We append to $l. Probably a line-at-a-time with fixed-width split approach would be shorter.
> 1 votes

# Answer
# Bash + GNU utils, 41

```
fold -$1|sed ":;s/^.\{,$[$1-1]\}\$/ &/;t"

```

String is input via STDIN, width is input by command-line arg:

```
ubuntu@ubuntu:~$ echo 'Programming
Puzzles
&
Code
Golf'|./ralign.sh 10
Programmin
         g
   Puzzles
         &
      Code
      Golf
ubuntu@ubuntu:~$

```
> 1 votes

# Answer
# Python 2, 151 bytes

```
s,n=input();N='\n'
for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]:
 while w:print w[:n].rjust(n);w=w[n:]

```

This is a adaptation of @xnor's answer above, as his does not properly handle newlines.

---

The `for` loop was changed from:

```
for w in s.split('\n'):

```

to:

```
for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]:

```

---

# Example

```
$ python main.py
"Programming\n\n\nPuzzles\n\n&\n\nCode\nGolf", 5
Progr
ammin
    g

Puzzl
   es

    &

 Code
 Golf

```
> 1 votes

# Answer
# C#, 143 bytes

```
(s,n)=>Join("\n",s.Split('\n').SelectMany(l=>(l.Any()?l:" ").Select((c,i)=>new{c,i}).GroupBy(o=>o.i/n,o=>o.c).Select(g=>Concat(g).PadLeft(n))))

```

Linq lets you make pretty gnarly expressions. `GroupBy` is useful here, but it's a shame they couldn't create function overloads taking the index.

Assign the lambda to a `Func<string, int, string>` to run it

Less golfed:

```
Func<string, int, string> Align = (s, n) => Join("\n",
    s.Split('\n')
     .SelectMany(l => (l.Any() ? l : " ")
         .Select((c, i) => new { c, i })
         .GroupBy(o => o.i / n, o => o.c)
         .Select(g => Concat(g).PadLeft(n))));

```
> 1 votes

# Answer
## Burlesque, 28 Bytes

Same as the version below, but treats line 1 as the number and the other lines as the string.

```
lng_riPpun{pPco{pP' lp}mu}Wl

```

Usage as in:

```
$ cat input.txt | blsq --stdin "lng_riPpun{pPco{pP' lp}mu}Wl"
Progr
ammin
    g
Puzzl
   es
    &
 Code
 Golf

```

Old Version (16 bytes):

```
{5co{5' lp}mu}Wl

```

Example:

```
blsq ) "Programming\nPuzzles\n&\nCode\nGolf"{5co{5' lp}mu}Wl
Progr
ammin
    g
Puzzl
   es
    &
 Code
 Golf

```
> 1 votes

# Answer
# Groovy, 63 bytes

Returns the correctly alligned string. Didn't know there was a padLeft (and padRight, padCenter) function until now.

```
f={s,n->s.split("(?<=\\G.{$n})|\n")*.padLeft(n," ").join("\n")}

```
> 1 votes

# Answer
# JavaScript ~~174~~ 136

```
function R(s,x){return s.replace(new RegExp(".{"+x+"}","g"),"$&\n").replace(/[^\n]*/g,function(m){
while(m.length<x)m=" "+m;return m;})}

```
> 1 votes

# Answer
# Ceylon, 107

```
String w(String s,Integer n)=>"\n".join{for(l in s.lines)for(p in l.partition(n))String(p).padLeading(n)};

```
> 1 votes

# Answer
# Matlab, 99 bytes

Thanks to @beaker for removing 6 bytes!

Using and anonymous function:

```
@(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0)))

```

Define the function and use `ans` to call it:

```
>> @(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0)))

ans =

@(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0)))

>> ans(['Programming' 10 'Puzzles' 10 '&' 10 'Code' 10 'Golf'], 5) %% 10 is line feed

ans =

Progr
ammin
    g
Puzzl
   es
    &
 Code
 Golf

```
> 1 votes

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


title: Bob the Bowman!

text:
# Question
Title: Bob the Bowman!
# Bob the Bowman

```
      o
    /( )\                                         This is Bob.
     L L                                          Bob wants to be an archer.
#############

    .
   / \          <--- bow                          So he bought himself a
  (c -)->       <--- arrow                        nice longbow and is about
  ( )/          <--- highly focused Bob           shoot at a target.
  L L
#############

___________________________________________________________________________________________
sky

                     Bob is a smart guy. He already knows what angle and
                     velocity his arrow has / will have. But only YOU know
                     the distance to the target, so Bob doesn't know if he
                     will hit or miss. This is where you have to help him.

     .                                                                                +-+
    / \                                                                                | |
   (c -)->                                                                              | |
   ( )/                                                                                +++
   L L                                                                                |
###########################################################################################

```

---

## Task

Your task is to render an ASCII art picture of Bob hitting or missing the target. For the calculation:

* Your program will receive `arrow_x,angle,velocity,distance` as comma-separated input in any order you wish.
* One ASCII character equals `1m`.
* The first character in the last line has the coordinates `(0,0)`, so the ground (rendered as `#`) is at `y=0`.
* Bob always stands on the ground, his `y` position does not change.
* There is no max `y`. However, the arrows apex should fit within the rendered picture.
* All input is provided as decimal integer.
* During calculation, assume the arrow is a point.
* The arrow origin is the arrow head `>` of a shooting Bob (see above). So given `arrow_x`, you have to calculate `arrow_y`. The left foot of Bob in the output has to match the `x` coord. of the shooting Bob.
* `distance` is the `x` coordinate of the target's *foot*. (ie. the middle of the target).
* All measurements are supplied in meters and degrees respectively.
* Attention: *The shooting Bob is never rendered, only used for calculations! See below for the two valid output-Bobs*
* Hitting the target means the arrows path crosses either one of the two leftmost target walls (`|`) (That is either (distance-1,3) or (distance-1,4). If at some point the arrow is within those 2m², place the X instead of the wall it hits. The target is always the same height and only its x position can change.). Corner hits or an arrow falling from the sky onto the target does not count.
* Standard earth g applies (9.81 m/s^2).
* `distance+1` is the end of the field, after that, everything is a miss and no arrow should be rendered.
* If the arrow hits the target in any other way (`distance-1` etc.), no arrow should be rendered.

## Miss

This is an example rendering of Bob missing (arrow enters ground at 34m, angle is 45°, time in air is 10s, velocity is ~50 - but there are a lot more possible inputs to cause this output. Just show your program uses the usual formulas to calculate physically "accurate" results.):

```
                                                                                +-+
                                                                                | |
  c\                                                                                | |
/( )                              v                                                     +++
 L L                              |                                                      |
###########################################################################################

```

## Hit

This is an example rendering of Bob scoring (arrow enters target (= crosses its path)):

```
                                                                                +-+
                                                                                >--X |
 \c/                                                                                | |
 ( )                                                                                +++
 L L                                                                                |
###########################################################################################

```

## Example

* `arrow_x` is 7. `arrow_y` is always 3.
* `angle` is `30°` or `0.523598776` radians.
* `velocity` is `13m/s`.
* `distance` is 20.

So in order to hit the target, the arrow has to cross `(19,3)` or `(19,4)`. Everything else will be a miss. In this case, the arrow will enter the ground (means `y` will be `<1.0`) at `12.9358m = ~13m` after `1.149s`.

---

## Limits & Scoring

* This is , so the shortest solution wins. There are no bonuses.
* Your *program* (as in *not function*) must accept input in the format described above, additional input is not permitted.
* You don't have to handle wrong/pointless/impossible inputs.
* Print to whatever is the shortest reasonable output for your language (std, file, ...).
* I don't care about trailing whitespace.
* *Tip:* Width of output is `distance+2`. The height is `apex+1`.

# Answer
# Ruby, 482

```
include Math
def f s,e,l
[s,' '*(l-s.size-e.size),e].join
end
alias p puts
X,o,V,d=$*[0].split(?,).map &:to_i
o*=PI/180
L=X+d
B='| |'
S=''
G=' L L'
p f S,'+-+',L
d.times{|x|y=3+x*tan(o)-(9.81*x**2)/(2*(V*cos(o))**2)
if x==d-1&&(3..5)===y
s='>--X |'
m=(3..4)===y
p f S,m ?B: s,L
p f ' \c/',m ?s: B,L
p f ' ( )',?+*3,L
p f G,'| ',L
elsif y<=1 || x==d-1
p f S,B,L
p f '  c\\',B,L
print f '/( )', y<1? 'V':' ',x
p f S,?+*3,L-x
print f G, y<1? '|':' ',x
p f S,'| ',L-x
break
end}
p ?#*L

```

## Ungolfed

```
include Math
def fill s,e,l
   [s,' '*(l-s.size-e.size),e].join
end
arrow_x,angle,velocity,distance = $*[0].split(',').map(&:to_i)
angle *= PI/180
length=arrow_x+distance
loss = '| |'
puts fill '','+-+',length
distance.times { |x|
  y = 3 + x*tan(angle) - (9.81*x**2)/(2*(velocity*cos(angle))**2)
  if x == distance-1 && (3..5)===y
    puts fill '',(3..4)===y ? '| |':'>--X |',length
    puts fill ' \c/',(3..4)===y ? '>--X |':'| |',length
    puts fill ' ( )','+++',length
    puts fill ' L L','| ',length
  elsif y<=1 || x==distance-1
    puts fill '',loss,length
    puts fill '  c\\',loss,length
    print fill '/( )', y<1? 'v': ' ', x
    puts fill '','+++',length-x
    print fill ' L L', y<1? '|': ' ', x
    puts fill '',' | ',length-x
    break
  end
}
puts ?#*length

```

### Method

The main equation here is:

Note: image taken from https://en.wikipedia.org/wiki/Trajectory\_of\_a\_projectile

Where,

```
y0: initial height (of arrow)
Ө: the angle
x: the position of the arrow
g: gravity (9.81)
v: velocity

```

What I'm doing is to loop through numbers from 0 to (distance -1) and in every iteration check to see if the arrow hits the ground (or the target)
> 2 votes

---
Tags: code-golf, ascii-art, physics
---


title: Maze generating one liner

text:
# Question
Title: Maze generating one liner
The famous C64 basic one liner

```
10 PRINT CHR$(205.5+RND(1)); : GOTO 10

```

prints a maze of slashes and backslashes.

```
\\/\\\//\/\////\\/\/
\/\///\\///////\//\/
/\\\//\//\////\\//\\
\////\//\//\/\\\\\\/
/\/\\///\\\\/\\\\/\\
\/\//\\\\\\//\/\////
/\//\\///\/\///\////
\/\\\//\\/\\\//\\/\/
//////\\/\\/\/\/\///
\\/\/\\////\/\/\\/\/

```

Read in such maze made of diagonal walls from stdin and print out the same maze with *horizontal* and *vertical* walls consisting of the wall character "#"

For example the small maze

```
/\\
\\/
///

```

translates to

```
     #####
     #   #
     # # # #
     # # # #
 ##### # # #
       #   #
   #########

     #####

```

To be precise, each isolated wall segment has the length of five characters, adjacent wall segments share a corner. Moving a character to the right/left/top/down in the matrix of slashes and backslashes corresponds to a diagonal translation by 2 characters in vertical and 2 characters in horizontal direction in the #-matrix.

More context can be found in the book 10 print.

# Answer
> 5 votes
# Python 3, ~~226~~ 224 bytes

My first Python golf, so probably very sub-optimal. It produces a whole lot of trailing whitespace, but there are no preceding newlines, and at most two preceding spaces. The input needs to be given by hand from command line (maybe someone knows a shorter way to get multiline input in Python...).

```
e,z,s=enumerate,'0',list(iter(input,""))
p=''.join(s)*5
r=[len(p)*[' ']for _ in p]
for y,l in e(s):
 for x,c in e(l):
  for i in range(-2,3):r[2*(x+y+(s>[z]))+i*(c>z)][2*(x+len(s)-y)+i*(c<z)]='#'
for l in r:print(''.join(l))

```

The idea is to initialize a huge array of spaces `r`, then iterate through the input and replace the spaces with `#` as needed, and finally print the whole array. A trick I used is to compare characters to `z = '0'` instead of testing equality to `'/'` or `'\'`, which saves a bunch of bytes.

# Answer
> 1 votes
# Julia, 258 bytes

A functional solution...

```
A=split(readall(STDIN))
q(i,j)=fld(i-1,j)
n,^ =A[].(3),q
f(i,j)=try A[1+i^5][1+j^5]<'0'?(i+j)%5==1:(i-j)%5==0catch 0end
h(i,j)=f(i+i^4,j)|f(i+(i-1)^4,j)
g(i,j)=h(i,j+j^4)|h(i,j+(j-1)^4)
for i=1:6length(A),j=-n-5:2n;print(" #"[1+g(i-j,i+j)],j==2n?"\n":"")end

```

In order of appearance: `f` covers '/' and '\\' by their 5\*5 bit patters, `h` folds every fifth and following line into a single line (recall "adjacent wall segments share a corner") and `g` does the same for the columns. Finally, `i-j,i+j` rotates the picture.

# Answer
> 1 votes
# JavaScript (ES6), 258

A function with the maze as a parameter, returning the output.

Unsure if it's valid, due to the input/output rules (it was fun anyway)

```
f=m=>([...m].map(c=>{if(c<' ')x=sx-=2,y=sy+=2;else for(x+=2,y+=2,d=c>'0',i=y-3*d,j=x-3*!d,c=5;c--;)o[i+=d][j+=!d]='#';},w=m.search`
`,h=m.match(/\n/g).length,sy=y=0,sx=x=h*2,o=Array(z=(w+h+1)*2).fill(' ').map(x=>Array(z).fill(x))),o.map(r=>r.join``).join`
`)

// LESS GOLFED

U=m=>(
  w=m.search`\n`,
  h=m.match(/\n/g).length,
  o=Array(z=(w+h+1)*2).fill(' ').map(x=>Array(z).fill(x)),
  sy=y=0,
  sx=x=h*2,
  [...m].forEach(c=>{
    if(c<' ')x=sx-=2,y=sy+=2
    else for(x+=2,y+=2,d=c>'0',i=y-3*d,j=x-3*!d,c=5;c--;)o[i+=d][j+=!d]='#';
  }),
  o.map(r=>r.join``).join`\n`
)

// TEST
out=x=>O.innerHTML+=x+'\n'

test=`\\\\/\\\\\\//\\/\\////\\\\/\\/
\\/\\///\\\\///////\\//\\/
/\\\\\\//\\//\\////\\\\//\\\\
\\////\\//\\//\\/\\\\\\\\\\\\/
/\\/\\\\///\\\\\\\\/\\\\\\\\/\\\\
\\/\\//\\\\\\\\\\\\//\\/\\////
/\\//\\\\///\\/\\///\\////
\\/\\\\\\//\\\\/\\\\\\//\\\\/\\/
//////\\\\/\\\\/\\/\\/\\///
\\\\/\\/\\\\////\\/\\/\\\\/\\/`
out(test),out(f(test))
```

```
<pre id=O></pre>
```

---
Tags: code-golf, ascii-art, maze
---


title: Download all StackExchange git repos

text:
# Question
Title: Download all StackExchange git repos
### Introduction

We all love StackExchange, therefore it would be essential to download all gems hidden on Stack Overflow repositories in the simplest possible way.

### Challenge/Task

Your task is to write a script or program which would:

1. Fetch the list of all (within current page) repositories under Stack Overflow GitHub account. This can be achieved either by using direct link, or by using API callback (in JSON format). Example URLs for public access:

```
https://github.com/StackExchange
https://api.github.com/users/StackExchange/repos

```
2. Parse the list either from HTML, JSON or whatever format you would have into standard git URL format (recognised by `git`), such as:

```
https://github.com/StackExchange/foo.git
https://github.com/StackExchange/foo
git@github.com:StackExchange/foo.git

```

The last one assumes that your public key is already added.
3. For each repository, `git clone` needs to be executed/invoked, for example:

```
git clone URL_to_1st_repo
git clone URL_to_2nd_repo
...

```
4. All repositories are cloned (destination doesn't matter) and should be present (not just echoed or silently processed).

### Assumptions

* We're assuming all necessary standard tools are installed (e.g. `git` command) and it's in your PATH..
* Assume that `github.com` fingerprint is already added into your system, e.g.

```
ssh-keyscan -H github.com >> ~/.ssh/known_hosts

```
* Assume that your public key to access the remote repository has been added to the system (this is only required when accessing via `git@`).
* We are not assuming any page or API rate limits.

### Rules & Requirements

* Smallest working/reproducible code with positive score wins.
* After execution, all repositories should be cloned and the script/program must exit without crashing.
* You can import libraries, but they must be made before the challenge. However, you're not allowed to alias libraries to make them shorter to use in your code. All libraries/tools which are provided by ubuntu/vivid64 sandbox (specified below) are not necessary to mention.
* All used languages or tools needs to be at least 1 year old to prevent too narrow submissions.

### Examples

You can find some useful examples at: How to clone all repos at once from Git.

### Sandboxes

* if you've got Vagrant installed, try running:

```
vagrant init ubuntu/vivid64 && vagrant up --provider virtualbox && vagrant ssh

```
* OpenRISC OR1K Javascript Emulator \- Running Linux With Network Support

However the `curl` doesn't always seems to work there (e.g. `curl -v ifconfig.co`).

# Answer
# Bash, 81 bytes

```
curl https://api.github.com/users/StackExchange/repos|tr -d ,|xargs -n1 git clone

```

Git will be fed a lot of invalid repos, but it will happily clone the valid ones.
> 3 votes

# Answer
### `sh` (92 characters)

Example using Linux shell:

```
curl https://api.github.com/orgs/StackExchange/repos|grep -o 'git@[^"]*'|xargs -L1 git clone

```

And alternative version `sh`, but 94 characters:

```
grep -o 'git@[^"]*'|xargs -L1 git clone<(curl https://api.github.com/orgs/StackExchange/repos)

```

**Explanation**

Downloads API page via `curl`, extracts URLs which starts with `git@`, then execute `git clone` for each match.
> 1 votes

---
Tags: code-golf, internet
---


title: Karel J. AlphaBot Sequence Generator

text:
# Question
Title: Karel J. AlphaBot Sequence Generator
# Scores

This section will be filled in as submissions are entered.

**Normal**

```
1. bopjesvla    Perl                54
2. edc65        Javascript (ES6)    91
3. name         language            score
4. name         language            score
5. name         language            score

```

**Bonus Round**

```
1. name   language   score
2. name   language   score
3. name   language   score
4. name   language   score
5. name   language   score

```

---

# Karel J. AlphaBot

**Background**

A popular introductory course to Java is Karel J. Robot (I'm using it myself). The robot interacts with a grid of streets (positive integer y-coordinates) and avenues (positive integer x-coordinates) as well as beepers, which can be placed and stored on the grid (note that Karel and any beepers can only exist on lattice points). Karel (the robot) is only to perform five actions: move forward by 1, turn left in place, put down a beeper, pick up a beeper, and turn itself off.

In my Computer Science class, one of our first assignments was to program Karel to learn how to turn right, turn around, and perform the combined action of moving forward by 1 and putting down a beeper. An assignment a few days later was to use these methods and write new methods to produce letters of the alphabet.

Naturally, once I finished this assignment, I wrote more methods to make every letter of the alphabet, as well as the ten numerical digits, and I plan to figure out how to make a sort of word processor out of the robot, where a string would be entered to STDIN and the robot would put beepers on the grid in a way that resembled the letters.

Every time I wrote `private void draw#` for each character `#`, I added a comment after it that would tell me abbreviations for the sequence of commands I'd need.

I have the following commands (written in pseudocode) at my disposal (clarification - these are the only *useful* commands).

```
Turn Left
    Rotate the robot 90˚ counterclockwise
    Abbreviated as "l"

Turn Right
    Rotate the robot 90˚ clockwise
    Abbreviated as "r"

Move
    Move one space forwards
    Abbreviated as "m"

Put Beeper
    Put a beeper on the spot that Karel is on
    Abbreviated as "p"

Drop Beeper
    Move, then Put Beeper
    Abbreviated as "d"

Turn Around
    Turn Left, then Turn Left
    Abbreviated as "a"

```

---

**Conditions**

The robot must proceed in the following order.

* The robot starts on the bottom left corner of the 5xN rectangle of minimal area the letter will be drawn in.
* The robot draws the letter.
* The robot moves to the bottom right corner of the rectangle.
* The robot moves two spaces to the right and *must face north/up*

Let's work through an example. Suppose we want to draw `A`. The location of the robot is the letter that indicates its direction (north, south, east, west). The letter is capitalized if the robot is on a spot with a beeper and lowercase if the robot is on a spot without a beeper. `o` represents spots with beepers and `.` represents spots without beepers.

As we will see later, `A` is this.

```
.ooo.
o...o
ooooo
o...o
o...o

```

Here is one possible solution.

```
Grids   .....   .....   .....   .....   .....   .....   .....   .....   .....
        .....   .....   .....   .....   .....   .....   .....   .....   .....
        .....   .....   .....   N....   E....   oE...   ooE..   oooE.   oooW.
        .....   .....   N....   o....   o....   o....   o....   o....   o....
        n....   N....   o....   o....   o....   o....   o....   o....   o....

Letters           p       d       d       r       d       d       d       a

        .....   .....   .....   .....   .....   n....   e....   .E...   .oE..
        .....   .....   .....   .....   N....   o....   o....   o....   o....
        ooWo.   oWoo.   Wooo.   Nooo.   oooo.   oooo.   oooo.   oooo.   oooo.
        o....   o....   o....   o....   o....   o....   o....   o....   o....
        o....   o....   o....   o....   o....   o....   o....   o....   o....

          m       m       m       r       d       m       r       d       d

        .ooE.   .oooe   .ooos   .ooo.   .ooo.   .ooo.   .ooo.   .ooo.
        o....   o....   o....   o...S   o...o   o...o   o...o   o...o
        oooo.   oooo.   oooo.   oooo.   ooooS   ooooo   ooooo   ooooo
        o....   o....   o....   o....   o....   o...S   o...o   o...o
        o....   o....   o....   o....   o....   o....   o...S   o...E

          d       m       r       d       d       d       d       l

```

The final `mml` to complete the fourth bullet is implicit because it appears in every letter and because I don't want to go back and add another two columns to everything in the above proposed solution.

Thus, one solution to make `A` is `pddrdddammmrdmrdddmrddddlmml`.

Note that this doesn't have to be your solution. Your algorithm can go through every column, putting beepers in the proper places and not relying on where other beepers have been placed or will be placed. No matter what your algorithm is, the robot can only place one beeper per space on the grid.

---

**The program**

Your program will take as its input a 5xN grid of what the grid for the letter is. Note that there is no robot on the input; the robot is assumed to be on the bottom left (southwest) corner, facing north.

The output will be the sequence of letters that are the shorthand for the sequence.

*Sample inputs*

```
.ooo.
o...o
ooooo
o...o
o...o

o...o.ooooo
o...o...o..
ooooo...o..
o...o...o..
o...o.ooooo

```

*Sample outputs*

```
pddrdddammmrdmrdddmrddddlmml

prmmmlmlmmdrdrdddlmlmmdrdrmmmdrddddlmmlprdddlmldmmrmrmdmlmldmmrdrddddrmmmdlmml

```

---

This is code golf, fellas. Standard CG rules apply. Shortest code in bytes wins.

---

# Bonus Round

**Rules**

If you want to participate in the bonus round, be sure to make your codes move-efficient! Below is a library of all of the 5x5 letters my program creates when it runs. The objective of the bonus round is to write a program that prints a sequence for `ABCDEFGHIJKLMNOPQRSTUVWXYZ` that contains as few moves as possible. There is no input to STDIN. Code will be graded *not* on the length of the code but on its "move score." The move score is designed to discourage sweeper algorithms that visit every point in the rectangle.

```
d: 1
l: 1
m: 4
p: 1
r: 1

```

**Letters**

```
.ooo.   oooo.   ooooo   oooo.   ooooo   ooooo   .oooo   o...o
o...o   o...o   o....   o...o   o....   o....   o....   o...o
ooooo   oooo.   o....   o...o   oooo    oooo.   o.ooo   ooooo
o...o   o...o   o....   o...o   o....   o....   o...o   o...o
o...o   oooo.   ooooo   oooo.   ooooo   o....   oooo.   o...o

ooooo   ....o   o...o   o....   ooooo   o...o   ooooo   oooo.
..o..   ....o   o..o.   o....   o.o.o   oo..o   o...o   o...o
..o..   ....o   oo...   o....   o.o.o   o.o.o   o...o   oooo.
..o..   o...o   o..o.   o....   o...o   o..oo   o...o   o....
ooooo   .ooo.   o...o   ooooo   o...o   o...o   ooooo   o....

oooo.   oooo.   ooooo   ooooo   o...o   o...o   o...o   o...o
o..o.   o...o   o....   ..o..   o...o   o...o   o...o   .o.o.
o..o.   oooo.   ooooo   ..o..   o...o   .o.o.   o.o.o   ..o..
oooo.   o..o.   ....o   ..o..   o...o   .o.o.   o.o.o   .o.o.
....o   o...o   ooooo   ..o..   ooooo   ..o..   ooooo   o...o

o...o   ooooo
.o.o.   ...o.
..o..   ..o..
.o...   .o...
o....   ooooo

```

The same procedure as the original challenge must be followed: letters must be drawn one at a time with a space separation between each letter.

Standard CG rules apply. Entry with the lowest move score wins.

---

---

---

To summarize, both codes will essentially do the same things. The first code should have a minimal number of bytes in the code, and the second code should use the smallest number of moves.

# Answer
> 5 votes
# perl -p0, ~~60 56~~ 54+2 bytes

**golf**

```
/
/;$:="m"x"@-";$_=mmmmlma.s/
/rmr$:a/gr.mml;y/.o/md/;

```

**notes**

```
/\n/; # capture the length of the first line
$:="m"x"@-"; # assign a string of m's with that length to $:
s/^/mmmmlmll/; # move to the starting position (-1,0)
s/\n/rmr$:rr/g; # replace all newlines with kareliage returns
y/.o/md/; # replace dots with moves and o's with drops
s/$/mml/; # append mml

```

# Answer
> 2 votes
# JavaScript (ES6), 91

A first try to the basic challenge.

Test running the snippet below in an EcmaScript 6 compliant browser (tested in Firefox)

```
// BASIC CHALLENGE ANSWER

f=s=>`mmmmr${[...s].map(c=>c<' '?[`mrmr${b}a`,b=m][0]:(b+=m,c>m?'pm':m),b=m='m').join``}ml`

/* ALSO ...
f=s=>`mmmmr${s.replace(/.|\s/g,c=>c<' '?[`mrmr${b}a`,b=m][0]:(b+=m,c>m?'pm':m),b=m='m')}ml`
*/

// TEST
// now, I need to implement Karel (and test it) to do a significant test
// (a super limited version of Karel, of course. Just what is needed)

Karel=(cmd, width, height) =>  // even if for this test we have a limited height to handle
{
  var grid = [...('.'.repeat(width)+'\n').repeat(height)],
  o = width+1,
  p = o*(height-2)+1,
  d = [-o, 1, o, -1], // direction offsets
  q = 0, // face up
  s = [...grid],
  steps = [];

  s[p] = 'n';
  steps.push([s.join``,'-']);

  [...cmd].forEach(c =>
    (
      c == 'l' ? q = q-1 &3
      : c == 'r' ? q = q+1 &3
      : c == 'a' ? q = q+2 &3
      : c == 'm' ? p += d[q]
      : c == 'p' ? grid[p] = 'o'
      : c == 'd' ? grid[p += d[q]] = 'o'
      : 0,
      s = [...grid],
      s[p] = s[p] == 'o' ? 'NESW'[q] : 'nesw'[q],
      steps.push([s.join``,c])
    )
  )
  return [s.join``,steps]
}
function go(cmd)
{
  var result = Karel(cmd,260,7)
  RESULT.innerHTML = result[0];
  STEPS.innerHTML = 'Steps:<br>'+result[1].map(x=>'<pre>'+x.join('\n')+'</pre>').join('')
}
function test(input)
{
  var exp = input.innerHTML;
  var cmd = f(exp);
  var result = Karel(cmd,20,7)
  CMD.innerHTML = cmd;
  RESULT.innerHTML = result[0];
  STEPS.innerHTML = 'Steps:<br>'+result[1].map(x=>'<pre>'+x.join('\n')+'</pre>').join('')
}
```

```
pre {
  float: left;
  border: 1px solid #888;
  margin: 2px
}

div {
  clear: both;
}

#CMD {
  word-break: break-all;
  white-space: normal;
  width:50%;
  overflow:auto;
}

#Y {
  width:50%;
}
```

```
Test cases (click to run a test)<br>
<pre id=T1 onclick='test(this)'>.ooo.
o...o
ooooo
o...o
o...o</pre>
<pre id=T2 onclick='test(this)'>o...o.ooooo
o...o...o..
ooooo...o..
o...o...o..
o...o.ooooo</pre>
<div>Command string:<br><pre id=CMD></pre></div>
<div>
Your Command:<br><input id=Y><button onclick='go(Y.value)'>-></button>
</div>
<div>Result:<br><pre id=RESULT></pre></div>
<div id=STEPS>Steps</div>
```

**BONUS CHALLENGE ANSWER - Score for full alphabet=869**

Test running the wnippet below in Firefox (better full screen)

As I don't like *fixed input/fixed output* challenges, you can try your input. Just remember, only letters will be printed.

```
// Optimal - working on small pattern but too slow (scale bad)
// So I build the total command letter by letter - that surely is NOT globally optimal

Key=sol=>sol.pos+' '+sol.setBits

Solve=(target, startRow, startDir, cmd)=>{
  // Target is a rectangle string 5x5, newline separated for total (5+1)*5 chars
  if (target[target.length-1] != '\n') target += '\n';

  var T = ~new Date()
  var width = 5, height = 5, startPos = (width+1)*startRow;
  var offset = [-width-1, 1, width+1, -1];
  var turns = [ "", "r", "rr", "l" ];
  var cmds = [ "m", "rm", "rrm", "lm", "d", "rd", "rrd", "ld" ];
  var visited = {}, scan =[[],[],[],[],[],[],[],[]], cscan;

  var baseSol = { steps:[], pos: startPos, dir: startDir, setBits: 0};
  var score = 0, j = 0
  var bit, key, turn, curSol, move, result
  var targetBits = 0;
  [...target].map((c,i)=>targetBits |= ((c=='o')<<i)) // 30 bits

  // First step, from outside, set bit in mask if it's set in target
  if (target[startPos]=='o') baseSol.setBits = 1<<startPos;
  console.log(target, targetBits.toString(16))
  visited[Key(baseSol)] = scan[0].push(baseSol);

  for (j = 0; j<99; j++)
  {
     cscan = scan[j];
     scan.push([])

     // console.log(`T: ${T-~new Date} J: ${j} SC: ${cscan.length}`)
     while (cscan.length > 0)
     {
        baseSol = cscan.pop()
        //console.log('Base', baseSol.dir, baseSol.pos, baseSol.setBits.toString(16), baseSol.steps.length)
        for(turn = 0; turn < 4; turn++)
        {
           // set direction, move and drop if you can
           curSol = {};
           curSol.dir = baseSol.dir + turn & 3;
           curSol.pos = baseSol.pos + offset[curSol.dir];
           // console.log(turn, curSol.dir, curSol.pos)
           if(target[curSol.pos] > ' '
              || curSol.dir == 1 && target[curSol.pos]=='\n'
             ) // if inside grid or on right border facing east
           {
              score = j + (turn == 2 ? 3 : turn == 0 ? 1 : 2);
              bit = 1 << curSol.pos;
              if (targetBits & bit)
                 curSol.setBits = baseSol.setBits | bit, move = 4 | turn;
              else
                 curSol.setBits = baseSol.setBits, score += 3, move = turn;
              if (!visited[key = Key(curSol)])
              {
                 curSol.steps = [...baseSol.steps, move] // clone and add
                 // task completed if on  right border and all bits ok
                 if (target[curSol.pos]>' ')
                 { // not on right border, proceed
                    visited[key] = scan[score].push(curSol)
                 }
                 else if (curSol.setBits == targetBits)
                 {
                    result = curSol.steps.map(v=>cmds[v]).join``
                    result = (cmd == ''
                    ? target[startPos]=='o' ? 'p' : ''
                    : target[startPos]=='o' ? 'd' : 'm') + result;
                    console.log(`T: ${T-~new Date} J: ${j} CMD: ${result}`)
                    return [cmd+result, curSol.pos / (width+1) | 0];
                 }
              }
           }
        }
     }
  }
  // Miserable failure!
  return []
}

console.log=(...x)=>LOG.innerHTML+=x+'\n';
// TEST
Karel=(cmd, width, height) =>  // even if for this test we have a limited height to handle
{
  var grid = [...('.'.repeat(width)+'\n').repeat(height)],
  o = width+1,p = o*(height-2)+1,d = [-o, 1, o, -1], // direction offsets
  steps = [],s = [...grid],q = 0; // face up

  s[p] = 'n';
  steps.push([s.join``,'-']);

  [...cmd].forEach(c =>
    (
      c == 'l' ? q = q-1 &3
      : c == 'r' ? q = q+1 &3
      : c == 'a' ? q = q+2 &3
      : c == 'm' ? p += d[q]
      : c == 'p' ? grid[p] = 'o'
      : c == 'd' ? grid[p += d[q]] = 'o'
      : 0,
      s = [...grid],
      s[p] = s[p] == 'o' ? 'NESW'[q] : 'nesw'[q],
      steps.push([s.join``,c])
    )
  )
  return [s.join``,steps]
}

var AlphabetMap = `.ooo..oooo..ooooo.oooo..ooooo.ooooo..oooo.o...o.ooooo.....o.o...o.o.....ooooo.o...o.ooooo.oooo..oooo..oooo..ooooo.ooooo.o...o.o...o.o...o.o...o.o...o.ooooo
o...o.o...o.o.....o...o.o.....o.....o.....o...o...o.......o.o..o..o.....o.o.o.oo..o.o...o.o...o.o..o..o...o.o.......o...o...o.o...o.o...o..o.o...o.o.....o.
ooooo.oooo..o.....o...o.oooo..oooo..o.ooo.ooooo...o.......o.oo....o.....o.o.o.o.o.o.o...o.oooo..o..o..oooo..ooooo...o...o...o..o.o..o.o.o...o.....o.....o..
o...o.o...o.o.....o...o.o.....o.....o...o.o...o...o...o...o.o..o..o.....o...o.o..oo.o...o.o.....oooo..o..o......o...o...o...o..o.o..o.o.o..o.o...o.....o...
o...o.oooo..ooooo.oooo..ooooo.o.....oooo..o...o.ooooo..ooo..o...o.ooooo.o...o.o...o.ooooo.o.........o.o...o.ooooo...o...ooooo...o...ooooo.o...o.o.....ooooo`.split('\n')
var LetterMap = [];
var l,row,m;

for (l=0;l<26;l++)
{
  for(m='',row=0;row<5;row++)
    m += AlphabetMap[row].substr(l*6,5)+'\n'
  LetterMap[l]=m;
}

print=Message=>{
  var Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  var startRow = 4, cmd=''
  var startDir = 0 // start facing UP
  ;[...Message].forEach(l => (
    [cmd, startRow] = Solve(LetterMap[Alphabet.search(l)], startRow, startDir, cmd),
    startDir = 1, // after each letter will be facing RIGHT
    cmd += '\n' // addin a newline (scoring 0) just for readability
  ))

  if (startRow != 4)
    cmd += 'mr'+'m'.repeat(4-startRow)+'rr' // on last row and facing up
  else
    cmd += 'ml' // ...facing up

  // Recalc score
  var score = 0
  ;[...cmd].forEach(c=>score += c=='m'? 4 : c<' '? 0: 1)

  var robot = Karel(cmd.replace(/\n/g,''), 26*7, 7)
  O.innerHTML=cmd+'\nScore:'+score
  R.innerHTML=robot[0]
  RS.innerHTML=robot[1].join`\n`
}

function test()
{
  var msg = I.value.toUpperCase()
  msg=msg.replace(/[^A-Z]/g,'')
  I.value=msg
  print(I.value)
}

test()
```

```
fieldset {
  padding:0;
}

pre {
  margin: 2px;
}

#RS {
  height: 200px;
  width: 50%;
  overflow:auto;
}

#I { width: 50% }
```

```
<fieldset ><legend>Message to print</legend>
<input id=I value='ABCDEFGHIJKLMNOPQRSTUVWXYZ'><button onclick='test()'>go</button></fieldset>
<fieldset ><legend>Command Result (newlines added for readability)</legend>
<pre id=O></pre></fieldset>
<fieldset ><legend>Robot output</legend>
<pre id=R></pre></fieldset>
<fieldset ><legend>Robot step by step</legend>
<pre id=RS></pre></fieldset>
<fieldset ><legend>log</legend>
<pre id=LOG></pre></fieldset>
```

---
Tags: code-golf
---