title: 8 adjacent squares

text:
# Question
Title: 8 adjacent squares
List the coordinates of 8 squares adjacent to `(0, 0)` in a 2d grid. Namely,

`[(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)]`

Order does not matter. The goal is to store the points into a list. Shortest answer wins.

# Answer
> 15 votes
# J - 12 char

The most natural representation of a list of pairs is a list of boxes containing each pair.

```
   }.4|.,{;~i:1
+---+----+---+---+-----+----+----+----+
|0 1|1 _1|1 0|1 1|_1 _1|_1 0|_1 1|0 _1|
+---+----+---+---+-----+----+----+----+

```

The magic happens in `{`, called *Catalogue*. It is essentially a generalized Cartesian product. The `}.4|.` part is for removing the `0 0` pair.

# Answer
> 15 votes
## Bash + grep 35

```
eval echo\ {-1..1},{-1..1}\;|grep 1

```

I know this doesn't beat the other bash answer but someone had to think of `grep`

# Answer
> 10 votes
# Ruby ~~29~~ ~~28~~ 26

```
(a=-1,1,0).product(a)[0,8]

```

### Bonus solution:

Ruby has many nice builtin array operators, but some of them have ridiculously long names.

```
[*[-1,1,0].repeated_permutation(2)].take 8

```

# Answer
> 9 votes
# Python 43 32

```
l=zip([1,-1,0]*3,[-1,1]*3+[0]*2)

```

Inspired by @primo

# Answer
> 7 votes
## GolfScript (17 chars)

```
9,4-{[.3/(\3%(]}%

```

Since the question calls for the points to be "listed in natural format", this leaves an array on the stack. To pretty-print it, append `p`, as in the online demo.

# Answer
> 6 votes
# Haskell 32

```
c=[0,1,-1]
_:l=[(a,b)|a<-c,b<-c]

```

The list is l (L).

# Answer
> 6 votes
# Brainfuck, 1093 characters.

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

```

# EDIT 209 characters

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

```

Original by Benjamin - i gave it another shot as well and got to 209 characters as well.

# Answer
> 4 votes
# Perl, 43 bytes

```
for$x(-1..1){$x|$_&&push@r,[$x,$_]for-1..1}

```

The result is stored in array `@r`. Explicitly it can be defined with 58 bytes:

```
@r=([-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1])

```

# Answer
> 4 votes
## J, 16 characters

```
   }.4|.,<@,"0/~i:1

```

Usage:

```
   }.4|.,<@,"0/~i:1
┌───┬────┬───┬───┬─────┬────┬────┬────┐
│0 1│1 _1│1 0│1 1│_1 _1│_1 0│_1 1│0 _1│
└───┴────┴───┴───┴─────┴────┴────┴────┘

```

Pretty ugly - especially dropping the `(0, 0)`. There's probably a better way.

# Answer
> 4 votes
# Mathematica 23

```
Most@Tuples[{-1,1,0},2]
(*
{{-1, -1}, {-1, 1}, {-1, 0}, {1, -1}, {1, 1}, {1, 0}, {0, -1}, {0, 1}}
*)

```

# Answer
> 4 votes
# Brainfuck, ~~217~~ 209 characters.

Only a bit worse than Java! 5x less than the other BF solution.

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

```

# Answer
> 3 votes
## Mathematica, 44 characters

```
Outer[List,d=Range@3-2,d]~Flatten~1~Drop~{5}

```

Well. Generates all 9 coordinates, flattens the list and drops the centre.

# Answer
> 3 votes
# Python 50:

```
l=[(a,b)for a in[1,0,-1]for b in[1,0,-1]];l.pop(4)

```

# Answer
> 2 votes
# Bash, 25 characters

Storing the list of coordinates as a bash array `a`:

```
a=({-1..1},{-1..1});a[4]=

```

Output:

```
$ a=({-1..1},{-1..1});a[4]=
$ echo ${a[@]}
-1,-1 -1,0 -1,1 0,-1 0,1 1,-1 1,0 1,1
$

```

# Answer
> 2 votes
# F# - ~~41~~ 36 bytes

```
[for i in 0..7->i*2/5-1,(i*5/4)%3-1]

```

# Answer
> 1 votes
# Python - ~~57~~ ~~54~~ 56

```
r=range(-1,2);list({(i,j) for i in r for j in r}-{(0,0)})

```

Improved to

```
r=[-1,0,1];list({(i,j) for i in r for j in r}-{(0,0)})

```

with storage of the variable

```
r=[-1,0,1];l=list({(i,j) for i in r for j in r}-{(0,0)})

```

# Answer
> 1 votes
# C++, 60

Let's do this an interesting way. Hint: "2" is ASCII 50.

```
char x[]="11123332",y[8],i;for(i=8;i--;)y[(i+2)%8]=x[i]-=50;

```

# Answer
> 1 votes
# Perl 6: 27 characters

Most simply:

```
$/=(-1..1 X -1..1)[^4,5..*]

```

Get the permutations of -1, 0, and 1 with itself, and hard-code skipping (0, 0). But that's no fun! I prefer things to be more complex: (50 characters)

```
$/=map {[.re,.im]},grep *.abs>0,(-1..1 X+ -i,0i,i)

```

# Answer
> 1 votes
## Python - 37 bytes

```
a=[(i*2/5-1,-i%3-1)for i in range(8)]

```

An alternative at 40:

```
a=zip([0,1,-1]*3,[0]*3+[1]*3+[-1]*3)[1:]

```

And a 42 that's also interesting:

```
a=0,1,-1;a=zip(sum(zip(a,a,a),()),a*3)[1:]

```

# Answer
> 1 votes
# Java 207 204

Way too much, I know, but its the best I could do right now...
I might think of something better...

```
class A{public static void main(String...a){int[][] l=new int[8][2];for(int x=-1,y,i=0;x<2;x++){for(y=-1;y<2;y++){if(x!=0||y!=0){l[i][0]=x;l[i][1]=y;System.out.print("("+l[i][0]+","+l[i][1]+")");i++;}}}}}

```

Sensibly:

```
class A {
    public static void main(String...a) {
        int[][] l = new int[8][2];
        for (int x = -1, y, i = 0; x < 2; x++) {
            for (y = -1; y < 2; y++) {
                if (x != 0 || y != 0) {
                    l[i][0] = x;
                    l[i][1] = y;
                    System.out.print("("+l[i][0]+","+l[i][1]+")");
                    i++;
                }
            }
        }
    }
}

```

# Answer
> 1 votes
# APL (13 characters)

```
1↓,∘.,⍨0 1 ¯1

```

Explanation:

```
1↓           ⍝ Drop the first element of
  ,          ⍝ an array that comes from the matrix formed by
   ∘.,⍨      ⍝ concatenating each element with every other element
       0 1 ¯1⍝ in this array [0,1,-1]

```

# Answer
> 0 votes
# PYG (27):

```
P(*ItPr((-1,0,1),repeat=2))

```

Nothing all that special, really.

In regular python:

```
from itertools import product
for i in product((-1,0,1),repeat=2): print i

```

# Answer
> 0 votes
# C, 73

```
main(i){for(i=0;i<9;i++)if(i-4)printf("%s(%d,%d)",i?",":"",i%3-1,i/3-1);}

```

# Answer
> 0 votes
# Mathematica: 41

This works most of the time ;)

```
Union[RandomInteger[2,{99,2}]-1]~Drop~{5}

```

Equivalently:

```
Drop[Union@RandomInteger[2,{99,2}]-1,{5}]

```

# Answer
> 0 votes
# Matlab: 53

Similar to my other answer:

```
unique(round(2*rand(99,2))-1,'rows');ans([1:4,6:9],:)

```

I couldn't index on the output of unique directly, and I couldn't find a way around that...

# Answer
> 0 votes
# Haskell 97

Too much for Haskell and definitely not as good as the other Haskell answer, but here's a different, albeit sucky, approach:

```
take 8 (zip (replicate 3 (-1) ++ replicate 3 1 ++ replicate 3 0) (concat (replicate 3 [-1,1,0])))

```

:D

# Answer
> 0 votes
# Scala, 56

Self-explanatory.

```
def x=List(-1,0,1);for{i<-x;j<-x;if i!=0|j!=0}yield(i,j)

```

Ungolfed:

```
def x=List(-1,0,1)
for{
  i <- x
  j <- x
  if i!=0 | j!=0
} yield(i,j)

```

# Answer
> 0 votes
# Perl, 42 characters:

```
@r=map[split","],grep/1/,glob"{-1,0,1},"x2

```

Uses the shell-like glob functionality to generate the list of strings `("-1,-1","-1,0","-1,1","0,-1","0,0","0,1","1,-1","1,0","1,1")`, discards strings that don't contain the character `"1"` (i.e. drop `"0,0"`), then splits the strings on comma to get the desired data structure.

## 41 characters:

```
@r=map[split x],grep/1/,glob"{-1,0,1}x"x2

```

abuses barewords: the strings are `("-1x-1","-1x0"`, etc.`)` and the split is done on the letter `x` instead.

# Answer
> 0 votes
# JavaScript (ES5) 52 bytes

```
[[n=-1,n],[n,0],[n,1],[0,n],[0,1],[1,n],[1,0],[1,1]]

```

---

# Javascript (ES5) (*algorithmic*) 57 bytes

```
for(a=-2,x=[];++a<2;)for(b=-2;++b<2;)a|b&&x.push([a,b]);x

```

# Answer
> 0 votes
## Fortran: ~~101~~ 96

Fortran supports complex variables, so we just store the 8 values as a set of complex numbers and get ourselves a list of tuples.

```
complex x(8);x=reshape([(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)],[8]);print*,x;end

```

Printing this to look nice might be a pain in the butt because printing the `real` and `aimag` components adds a lot of bytes. But we can deal with floats.

---

Old answer:

```
complex x(8);k=1;do i=-1,1;do j=-1,1;if((j==0).and.(i==0))cycle;x(k)=cmplx(i,j);k=k+1;enddo;enddo;end

```

This abuses implicit typing (as usual).

# Answer
> 0 votes
# SQL 109 (that far)

```
create table a(x int);insert into a values(-1),(0),(1);select a.x,b.x y from a,a b where not(a.x=0 and b.x=0)

```

if you want to retest it, you can prepend `drop table if exists a;`

# Answer
> 0 votes
**C#** 140 chars

Shorter version:

```
List<string> a=new List<string>();for(int i=0,m=-1;i<3;i++,m++){for(int j=0,n=-1;j<3;j++,n++){if(m==0 && n==0)continue;array.Add(m+","+n);}}

```

Easy to read version:

```
List<string> array = new List<string>();
for (int i = 0, m = -1; i < 3; i++, m++)
{
    for(int j = 0, n = -1; j < 3; j++, n++)
    {
         if (m == 0 && n == 0) continue;
         array.Add(m + "," + n);
    }
}

```

---
Tags: code-golf
---


title: The Quickest Fox in the East

text:
# Question
Title: The Quickest Fox in the East
In the spirit of Hello world! with NO repetition

Write a program that prints the string "the quick brown fox jumps over the lazy dog" with optional newline. The entire program must not repeat any characters.

Note that the string to be printed *does* repeat characters, so you will have to get around that limitation somehow.

Note that the winning condition is , i.e. *the highest-voted answer* wins.

Update: To make this a little easier, repetition is allowed but you must attempt to minimize it. Programs with less (or no) repetition are given precedence over programs with some repetition.

# Answer
> 33 votes
# Microsoft Word from 97 to 2003 (and some Mac Word versions) — 10 characters

No repetitions, but doesn't quite match specs - 10 characters:

```
=rand(2,1)

```

Output:

```
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.

```

Matches specs, other than capitalization and punctuation, one repetition - 10 characters:

```
=rand(1,1)

```

Output:

```
The quick brown fox jumps over the lazy dog.

```

Newer versions of Microsoft Word use `=rand.old(1,1)` which duplicates `d` and `1`.

There might be a way to use a field `{=SUM(3,-2)}` as input to rand() but my installation is having issues with fields -- namely, they're not working...

"Bob" has confirmed that `{=SUM(3,-2)}` (with some difficulty) can be used to replace the first `1`, but `=` is repeated...

```
=rand({=SUM(3,-2)},1)

```

Provided you get Word to update `SUM` first, the output is:

```
The quick brown fox jumps over the lazy dog.

```

# Answer
> 17 votes
# Sclipting — 36 characters

```
덆둥긇굵늖꽫긆깲닷덮긂롦닲롸껂걪덖륰댲걯덦넬댢건늆넠닆굺뎒걤닶댬首坼

```

(expects empty input)

## Explanation:

```
Push the string "the quick brown ,fo,x, jumps ove,r the lazy dog,"
덆둥긇굵늖꽫긆깲닷덮긂롦닲롸껂걪덖륰댲걯덦넬댢건늆넠닆굺뎒걤닶댬
Retrieve last character from the string (",")
首
Regular expression string-split
坼

```

The result is the list `["the quick brown ", "fo", "x", " jumps ove", "r the lazy dog", ""]`, which is automatically concatenated into a single string for output.

# Answer
> 13 votes
## Perl 6 (76 chars, no doubles)

The script (will be mangled by the board software, but there's En Space up to Thin Space and NL and LF and tab)

```
say　EVAL    lc q{<the Quiţk Brown fïX jUmpS ůvťɲ Tɨå ìšzY dOg>~&(127.CHR
x
43)}

```
* It uses EVAL (thanks again for making it uppercase) and `<foo bar>` quote words which supports all the special space characters as word separators.
* `say` joins the list of strings using space, works nicely here :)
* Next I use `~&` and 127 to bit shuffle to plain ascii. Extra complication: `'Ŭ'.lc` becomes `'ŭ'` so that becomes an `s` instead of the `r` I needed. Adding 128 some extra times helps :)

A version with backslash escapes instead of unicode characters to show they're all different

```
say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)}

```

If you want to verify they're all unique, use this script (I used `Qb"string"` to have basic quoting with only backslash escapes)

```
.say for
Qb"say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)}"
.comb.Bag.grep(*.value > 1).map: {.key.ord.base(16) ~ " $_"  }

```

Or execute it directly using

```
EVAL Qb"say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)}"

```

# Answer
> 10 votes
## PHP - 67 bytes

```
<?echo$g^¶¥€¼½ˆ•.${~˜}=ÂÍåœÌýü¡¦Åþ¾’‹Ï†£‘Æ²áºëÓâæÝ—ß™ó–Ž¸·³ø‰ï®ÜØÔ;

```

*Copy-Paste, save as Latin-1 (Ansi).*

This is a 7-byte xor-cipher, using the string `¶¥€¼½ˆ•` for salt.

One repeated character: `$`.

# Answer
> 0 votes
# Haskell, 71 characters

```
map(\c->chr$mod(ord c)128)"tŨeఠquiţkĠbŲɯwnȠfѯxРjѵŭŰsܠůvťѲठѴѨѥਠlšzyଠɤկg"

```

Yet another 7-bit modulo solution.

Repeated characters:

```
c 3
d 2
m 2
o 2
r 2
( 2
) 2
" 2

```

First time golfing with Haskell; anyone more experienced in the language, feel free to improve. I wanted to make the anonymous function point-free to avoid having to mention a variable twice, but I don't know if it'd be a net benefit.

---
Tags: popularity-contest, restricted-source
---


title: aHHHH! The Beasts are HHHHere!

text:
# Question
Title: aHHHH! The Beasts are HHHHere!
As we learned from the IBM PC AT, YouTube (see video), Wikipedia (see article), and Sesame Street:

# **The letter `H` is the *most merciless letter of the alphabet*!**

*(Even when actually composed from two elements in Code Page 437. In fact, it's even MORE merciless that way.)*

Like the Aliens in, uhm...er... *Aliens*, Beasts relentlessly pursue all who would dare come near their eggs. There is no reasoning with them. You must squash them if not to perish.

For this scenario we will assume you're down to your last life, and you've met plain Beasts in a terrain with no eggs (as in the Wikipedia screenshot). You don't have a numeric keypad and can only move directly up/down/left/right...but the beasts apparently have one, and can move diagonally on their turn.

A Beast's choice of move among its options will be the one that minimizes distance from the player. If the distances are equal then tie breaking is done favoring left+up over right+down, but here's the disambiguation matrix to be explicit about it...lowest number to tie-break:

```
1 3 4
2 H 5
6 8 7

```

A beast never sleeps, but they are fortunately a bit slower than the player. They move *every other turn* (giving the player a head start by beginning their alternations on the second turn). They must move if a move is possible, regardless of if that takes them further from the player.

You crush a beast if you move a train of movable walls where it was sitting in a closed gap. These plain beasts are worth 2 points a head.

# Input

1. A pair of integers indicating a map's size in columns then rows.
2. Row count of lines of input, each of the column size...containing either a solid wall (`#`), a movable wall (`~`), a beast (`H`), the player (`O`) or just a space.
3. Input that will be either U, D, L, R indicating an *attempted* move by the player... or W to just wait. Note that attempting to push a movable wall which is blocked is legal input, it just will result in no action.

# Output

1. `aHHHH!` if the beasts killed the player...or nothing if the player won with no beasts remaining
2. The score

*(Note: For debugging purposes and/or amusement, you'll probably want to be able to output the state at each step; but that's too long to post here.)*

# Clarifications

* Maps are guaranteed to be bounded by solid walls.
* The order of who moves in a turn matters for the outcome. Thus: The player always goes first, then the beasts are given an ordering based on their *initial map position* if you were sweeping across the screen top to bottom left to right. *(A row 1 beast moves before a row 2 beast, and two beasts on the same row it would be the one with the lowest column number that would move before the other)*
* Diagonal moving beasts can move into any open adjacent diagonal space, regardless of if it requires squeezing between walls.
* A player can push any number of movable walls in a line provided that there's a space or a beast on the other end. But trying to push a train of walls into a Beast that is not pinned between walls treats the Beast as a wall, and won't allow the move.
* A Beast's move decision during a turn is based on the player's location at the *beginning* of the turn. Its desired optimization of "distance to player" is through an "as the crow flies" calculation. Any approximation which would give the same result as measured from the center of its square to the center of the player's square is fine.
* If a Beast can't make what would have been its first preferred move in a turn because a higher priority Beast took its spot, it will take its next best choice as opposed to staying in place (if a move is still possible).

# Sample Cases

### Simple Crush

*Input*

```
5 3
#####
#O~H#
#####
R

```

*Output*

```
2

```

### Preference Matrix -\> Death

*Input*

```
5 5
#####
#O  #
# ~ #
#  H#
#####
WWDW

```

*Output*

```
aHHHH!
0

```

### Preference Matrix -\> Win

*Input*

```
5 5
#####
#O  #
# ~ #
#  H#
#####
WRD

```

*Output*

```
2

```

### Waiting For the Reaper

*Input*

```
5 5
#####
#O  #
# ~ #
#  H#
#####
WWW

```

*Output*

```
aHHHH!
0

```

### Successful Defeat in the Wikipedia Scenario

*Input*

```
40 23
########################################
#~      ~ ~~  ~  ~ ~~   ~ ~~    ~ ~ ~~ #
#~~ ~          ~~   ~   ~ ~~         ~ #
#~# ~~   ~~~~      ~  ~~~~  ~    ~~~  ~#
# ~        ~   ~ ~~ #~~       ~        #
#~~  ~~~   ~ ~ ~      ~ ~~ ~  ~  ~  ~  #
#     ~~  ~  ~ ~ ~~~       H    ~  #~  #
#  O~  ~  #  ~~~ ~      ~ ~~  ~  ~ ~~  #
#       ~ ~H~~   ~~ ~ #        ~~   ~  #
# ~~         ~ ~~~  ~~   ~~~~      ~  ~#
#~  ~    ~~~  ~   ~        ~   ~ ~~  ~~#
#     ~      # ~ ~~  ~~~   ~ ~ ~ #    ~#
#~ ~ ~~  ~  ~   H     ~~  ~~ ~ ~ ~~~   #
#       ~   ~   ~   ~  ~     ~~~ ~     #
# ~~  ~  ~ ~~   ~       ~ ~ ~     ~    #
#      ~~   ~   ~  ~         ~      ~~ #
#~ ~     #    ~~~~  ~    ~~~H   # ~    #
#  ~   ~ ~   ~        ~          ~~  ~ #
#  ~   ~     #~  ~   ~~  ~  ~         ~#
# ~~ ~ ~  ~~                ~   ~      #
#    ~~~        ~ ~~  ~  ~  ~   ~      #
# ~ ~     ~            ~~   ~   ~  ~   #
########################################
RRRUWWWRRRURWWWWRDRRWWRDWWWWD

```

*Output*

```
8

```

Map provided by me, moves and output by @bobbel, corroborated by myself and @Allbeert.

# Winning Criteria

I think this is golfable, so I'll go with code golf rules unless people complain.

# Extra Credit

Playable Unicode implementation with the double-wide characters to resemble the image!

# Answer
> 3 votes
# Perl 6: 741 characters, 758 bytes

The golfed version is at the bottom, since it's basically linenoise. Above it is my pre-golfed version. Both are interactive (they'll read as many commands from the input file as they can and then move on to using STDIN to get commands). They try to use the original characters and colors.

Usage is like `perl6 beast.p6 beast-input`:

```
use Term::ANSIColor;
class BeastGame {
    enum BeastParts <None Player Beast M-Wall S-Wall>;

    has @.board;
    has Int $.turn = 0;
    has Int $.score = 0;

    method indices (\matcher) {
        @.board.pairs.map: {
            .key*i X+ .value[].pairs.map: {
                .key if .value ~~ matcher
            }
        }
    }
    multi postcircumfix:<[ ]> (BeastGame \SELF, Complex \c) is rw { SELF.board[c.im][c.re] }

    has Complex $!player;
    method player { $!player = $.indices(Player)[0] }
    method Bool { so $.indices(Player) & $.indices(Beast) }

    method new (@lines) {
        my @board = @lines.map:
            {[ %(' ',<O H ~ #> Z=> None, Player, Beast, M-Wall, S-Wall){ .comb } ]}

        self.bless: :@board
    }
    method gist {
        state @symbol-map = map {colored .key, .value~' on_black'},
            ('  ',<◄► ├┤ ▒▒ ██> Z=> <default cyan red green yellow>);

        @.board.map({ @symbol-map[@$_].join }).join("\n")
    }

    method step ($d) {
        my $direction = %(:W(0), :L(-1+0i), :R(1+0i), :U(-1i), :D(1i)){$d};
        $direction // return self;
        self.move($.player,$direction);

        if ++$!turn %% 2 {
            for $.indices(Beast).eager -> $c {
                for (-1-1i,-1+0i,-1i,1-1i,1+0i,-1+1i,1+1i,1i,0i)\
                        .sort({abs $c + $^d - $!player})
                {
                    last if self.move($c, $_).defined;
                }
            }
        }

        self;
    }
    method move ($cur, $by) {
        return $cur if $by == 0;

        my $to = $cur + $by;
        my &cur-is  = { self[$cur] ~~ $^o }
        my &next-is = { self[$to]  ~~ $^o }
        return if cur-is S-Wall;
        (self[$to], self[$cur]) = (self[$cur], None)
            if next-is None
            # Move wall
            or cur-is Player | M-Wall and next-is M-Wall and self.move($to, $by)
            # Kill Player
            or cur-is Beast  and next-is Player
            # Squish Beast
            or cur-is M-Wall and next-is Beast  and self[$to+$by] ~~ M-Wall|S-Wall and $!score += 2
    }
}
my $width = get.words[1];
my $game  = BeastGame.new(lines[^$width]);
my @commands = '',lines.comb,{$*IN.get.comb}...*;

while $game {
    $game.step: @commands.shift;
    print "\e[2J";
    print "\e[H";
    say $game;
}

say "aHHHH!" unless $game.player;
say $game.score;

```

The golfed version:

```
my ($u,$s,$m)=0,0;my@b=lines[^get.words[1]].map:{[%(' ',<O H ~ #>Z=>^5){.comb}]}
my@a='',lines.comb,{$*IN.get.comb}...*;sub g(\c)is rw {@b[c.im][c.re]}
my&n=->\o{@b.kv.map:{$^k*i X+$^v[].kv.map:{$^l if $^w==o}}}
my&p={$m=n(1)[0]}
my&M=->$c,$b{my$t=$c+$b;my&c={$^o==g $c}
my&x={$^o==g $t}
c(4)??0!!$b??(($c,$t)».&g=(0,g $c)
if x(0)||c(1|3)&&x(3)&&M($t,$b)||c(2)&&x(1)||c(3)&&x(2)&&2 <g($t+$b)&&($s+=2))!!1}
while n(1)&n(2) {for 1
{M p,%(:W(0),:L(-1),:R(1),:U(-1i),:D(1i)){@a.shift}//last;if $u++%2
{for n(2).eager ->$c{last if M $c,$_
for(-1-1i,-1+0i,-1i,1-1i,1+0i,-1+1i,1+1i,1i,0i).sort({abs $c+$_-$m})}}}
say "\e[2J\e[H",join "\n",map {[~]
(map {"\e[$^v;40m$^k\e[0m"},'  ',<39 ◄► 36 ├┤ 31 ▒▒ 32 ██ 33>)[@$_]},@b}
say "aHHHH!" if !p;say $s;

```

Happy Easter!

# Answer
> 15 votes
# Java, 1,843

My first try of solving this puzzle with Java. I know, that there are a lot of improvements to make it shorter. But in the end it works for now.

To try it, you have to create a class `C` and paste the code. `args[0]` (strictly speaking `a[0]`) is for input. The print method of the map is not included since it's not necessary for the puzzle output.

```
class C{static char                    [][]C;static int A=
0,B=0,D=0,E=0,F=0,G                    = 0 ; public static
void main(String[]a                    ){String []b= a[0].
split("\n");int c =                    Byte. decode(b [0].
split(" ")[1]); G=a                    [ 0 ] . replaceAll(
"[^H]","").length()                    ; String d = b [ b.
length - 1 ] ;C=new                    char[c][];for(int e
=1;e<b.length-1;e++                    ) C [ e - 1 ]=b[e].
toCharArray ( ) ; f                    ();boolean X= 0> 1;
for ( char  g : d .                    toCharArray ( ) ) {
switch(g){case 'U':                    h(0,-1);break; case
'D':h(0, 1); break;                    case 'L':h( -1, 0);
break;case'R':h(1,0                    );}if(X)i();X=!X;f(
);}System.out.print                    (D);}static void f(
){for(int a= 0;a<C.                    length;a++)for( int
b=0;b<C[a].length;b                    ++)if(C[a][b]=='O')
{A=b;B= a;}}static void h(int x,int y){E =x;F =y;switch(C[
B +y][A +x]){case 'H':g();break;case ' ':j(A,B);break;case
'~':k();}}static void i(){if(G<1){return;}int[][]l=new int
[G][];int m=0;for(int r=0;r<C.length;r++){for(int c=0;c<C[
r].length; c++){if(C[r][c]=='H'){l[m++]=new int[]{c,r};}}}
for(int[]n:l){o(n[0],n[1]);}} static void o(int a, int b){
int[]c=d (a,b);E=c[0];F =c[1];if(E !=0||F !=0){ j(a,b);} }
static int[]d(int a,int b){int[][]d={{1,3,4},{2,0,5},{6,8,
7},};int[]e=new int[]{0,0};double f=999;for(int r=-1;r<2;r
++){for(int c=-1;c<2;c++){if(C[b+r][a+c]==' '||C[b+r][a+c]
=='O'){int g=a+c-A;                    int h=b+r-B; double
i=Math.sqrt(g*g+h*h                    );if(i<f){e=new int
[]{ c,r};f =i;}else                    if(i==f){if(d[r+1][
c+1]<d[e[1]+1][e[0]                    +1]){e=new int[]{c,
r};}}} }}return e;}                    static void k(){if(
p(E,F,false)){q(E,F                    );} }static void q(
int x,int y){switch                    (C[B+y][A+x]){ case
'~':q(x+E,y+F);case                    'H':case ' ':j(A+x-
E,B+y- F);}} static                    boolean p(int x,int
y,boolean h){switch                    (C[B+y][ A+x]){case
' ':return !h; case                    '~':return h?h:p(x+
E,y +F, false);case                    'H':return h?!h:p(x
+E , y+ F, true) ;}                    return h&&C[B+y][A+
x] == '#' ; }static                    void j(int a,int b)
{char c=C[b][a];if(                    C[b+F][a+E]=='O'){g
();}else if(C[b+F][                    a+E]=='H'){D+=2;G--
;c=C[b][a];C[b][a]=                    ' ';}else{C[b][a]=C
[b+F][a+E];}C[b+F][                    a+E]=c;}static void
g () { System .out.                    print("aHHHH!\n"+D)
;     System      .                    exit  ( 0  ) ;  } }

```

---

To run it, try for example:

```
root@host:/cygdrive/c/workspace/project/bin> java C "5 5
> #####
> #O  #
> # ~ #
> #  H#
> #####
> WWDW"
aHHHH!
0
root@host:/cygdrive/c/workspace/project/bin>

```

---

Output of the last big scenario one turn before a beast eats the player:

```
████████████████████████████████████████████████████████████████████████████████
██▓▓            ▓▓  ▓▓▓▓    ▓▓    ▓▓  ▓▓▓▓      ▓▓  ▓▓▓▓        ▓▓  ▓▓  ▓▓▓▓  ██
██▓▓▓▓  ▓▓                    ▓▓▓▓      ▓▓      ▓▓  ▓▓▓▓                  ▓▓  ██
██▓▓██  ▓▓▓▓      ▓▓▓▓▓▓▓▓            ▓▓    ▓▓▓▓▓▓▓▓    ▓▓        ▓▓▓▓▓▓    ▓▓██
██  ▓▓                ▓▓      ▓▓  ▓▓▓▓  ██▓▓▓▓              ▓▓                ██
██▓▓▓▓    ▓▓▓▓▓▓      ▓▓  ▓▓  ▓▓            ▓▓  ▓▓▓▓  ▓▓    ▓▓    ▓▓    ▓▓    ██
██          ▓▓▓▓    ▓▓    ▓▓  ▓▓  ▓▓▓▓▓▓                        ▓▓    ██▓▓    ██
██          ▓▓▓▓    ██    ▓▓▓▓▓▓  ▓▓            ▓▓  ▓▓▓▓    ▓▓    ▓▓  ▓▓▓▓    ██
██              ▓▓  ▓▓  ▓▓▓▓      ▓▓▓▓  ▓▓  ██                ▓▓▓▓      ▓▓    ██
██  ▓▓▓▓                  ▓▓  ▓▓▓▓▓▓    ▓▓▓▓  ├┤  ▓▓▓▓▓▓▓▓            ▓▓    ▓▓██
██▓▓    ▓▓    ├┤◄►▓▓▓▓▓▓├┤  ▓▓      ▓▓                ▓▓      ▓▓  ▓▓▓▓    ▓▓▓▓██
██          ▓▓            ██  ▓▓  ▓▓▓▓    ▓▓▓▓▓▓      ▓▓  ▓▓  ▓▓  ██        ▓▓██
██▓▓  ▓▓  ▓▓▓▓    ▓▓    ▓▓                  ▓▓▓▓    ▓▓▓▓  ▓▓  ▓▓  ▓▓▓▓▓▓      ██
██              ▓▓      ▓▓      ▓▓      ▓▓    ▓▓├┤        ▓▓▓▓▓▓  ▓▓          ██
██  ▓▓▓▓    ▓▓    ▓▓  ▓▓▓▓      ▓▓              ▓▓  ▓▓  ▓▓          ▓▓        ██
██            ▓▓▓▓      ▓▓      ▓▓    ▓▓                  ▓▓            ▓▓▓▓  ██
██▓▓  ▓▓          ██        ▓▓▓▓▓▓▓▓    ▓▓        ▓▓▓▓▓▓        ██  ▓▓        ██
██    ▓▓      ▓▓  ▓▓      ▓▓                ▓▓                    ▓▓▓▓    ▓▓  ██
██    ▓▓      ▓▓          ██▓▓    ▓▓      ▓▓▓▓    ▓▓    ▓▓                  ▓▓██
██  ▓▓▓▓  ▓▓  ▓▓    ▓▓▓▓                                ▓▓      ▓▓            ██
██        ▓▓▓▓▓▓                ▓▓  ▓▓▓▓    ▓▓    ▓▓    ▓▓      ▓▓            ██
██  ▓▓  ▓▓          ▓▓                        ▓▓▓▓      ▓▓      ▓▓    ▓▓      ██
████████████████████████████████████████████████████████████████████████████████

```

Without silly line spaces: http://pastebin.com/raw.php?i=QhpxKcCT

So the players way is ending after the moves `RRDDDRRRWW`, because on the last `W`ait, the beast to the left will go to the right to eat the player.

---

Another example of the original big map but different moves:

http://pastebin.com/raw.php?i=nBWjC3PZ

See this animation: http://youtu.be/0DIhEhjWd6s

---

And the last example with original map and different moves (according to the new beast movement rules):

http://pastebin.com/raw.php?i=NNmgzx7U

See on youtube: http://youtu.be/jXPzL88TU2A

# Answer
> 5 votes
# C - ~~1004~~ ~~984~~ 917

Ahh, the beauty of C. Following the spirit of the other answer, I tried to format mine as well :)

I imagine there are still some improvements here and there, but this was really fun to write and golf. The character count includes all necessary spaces and new lines.

```
#define M(y,x,c) {t[y][x]=32;t[p][q]=c;y=p;x=q;}
   #define E {printf("aHHHH!\n%d",Z);exit(0);}
    #define A sqrt(pow(X-Q,2)+pow(Y-P,2))*30
           #define L (char)(m[s]>>8)
            #define G (char)(m[s])
             #define B(b) if(T==b)
              #define J M(Y,X,79)
               #define T t[P][Q]

r,c,X,Y,H,i,j,k,Z,p,q,P,Q,u,v,s,w,m[99],b[8]={
-1,255,65280,65281,1,511,257,256},t[999][999],
x[99],y[99];main(){char N[99];m[85]=b[2];m[68]
=256;m[76]=255; m[82]=1; scanf("%d %d",&c,&r);
for(;P<r;P++)                    for(Q=0;Q<c&&
scanf("%c",&T                    );T-10&&T-13?
Q++:Q){B(79){                    Y=P;X=Q;}B(72
){y[H]=P ;x[H                    ++]=Q;}}scanf
("%s",N);for(                    ;i<strlen(N);
i++){s=N[i];P                    =p=Y+L;Q=q=X+
G;B(32)J B('~')                  {while(P+=L,Q
+=G,T=='~');B                    (72){u=P+L;v=
Q+G;if(t[u][v]                   ==35||t[u][v]
=='~'){Z+=2;T=                   '~';J}}B(32){
T='~';J}}else                    B(72)E if(r=!r)
for(j=0;j<H;j                    ++){P=y[j];Q=
x[j];if(T-72)continue;v=A;s=0;for(k=0;k<8;k++)
{P=y[j]+(char)(b[k]>>8);Q=x[j]+(char)(b[k]);u=
A;B(32)if((c=v-u+99)>s){s=c;q=Q;p=P;}B(79)E}if
(s)M(y[j],x[j],72)}}printf("%d",Z);}//////////

```

I tested this with all the sample cases and a few more of mine, and it seems to be working properly. If anyone finds any situation in which it doesn't answer properly, please let me know.

Input is from stdin, and output to stdout. There are no checks for incorrect input. And, it returns the score if the player gets eaten, or if the player is alive after all movements are executed (even if there are still `H`'s around.

Ungolfed version:

```
#define M(y,x,c) {t[y][x]=32;t[p][q]=c;y=p;x=q;}
#define E {printf("aHHHH!\n%d",Z);exit(0);}
#define A sqrt(pow(X-Q,2)+pow(Y-P,2))*30
#define L (char)(m[s]>>8)
#define G (char)(m[s])
#define B(b) if(T==b)
#define J M(Y,X,79)
#define T t[P][Q]

r, c, X, Y, H, i, j, k, Z, p, q, P, Q, u, v, s, w, m[99], b[8] = { -1, 255,
        65280, 65281, 1, 511, 257, 256 }, t[999][999], x[99], y[99];
main() {
    char N[99];
    m[85] = b[2];
    m[68] = 256;
    m[76] = 255;
    m[82] = 1;
    scanf("%d %d", &c, &r);
    for (; P < r; P++)
        for (Q = 0; Q < c && scanf("%c", &T);T-10&&T-13?Q++:Q) {
            B(79) {
                Y=P;
                X=Q;
            }
            B(72) {
                y[H]=P;
                x[H++]=Q;
            }
        }

    scanf("%s", N);
    for (; i < strlen(N); i++) {
        s = N[i];
        P = p = Y + L;
        Q = q = X + G;
        B(32)
            J
        B('~') {
            while (P += L, Q += G, T=='~');
            B(72) {
                u=P+L;
                v=Q+G;
                if(t[u][v]==35||t[u][v]=='~') {
                    Z+=2;
                    T='~';
                    J
                }
            }
            B(32) {
                T='~';
                J
            }
        } else B(72)E
        if (r = !r)
            for (j = 0; j < H; j++) {
                P = y[j];
                Q = x[j];
                if (T-72)
                continue;

                v = A;
                s = 0;

                for (k = 0; k < 8; k++) {
                    P = y[j] + (char) (b[k] >> 8);
                    Q = x[j] + (char) (b[k]);
                    u = A;
                    B(32)
                        if ((c = v - u + 99) > s) {
                            s = c;
                            q = Q;
                            p = P;
                        }

                    B(79)
                        E
                }
                if (s)
                    M(y[j], x[j], 72)
            }
    }
    printf("%d", Z);
}

```

---
Tags: code-golf, game, maze
---


title: Convert image pixels to quadruples

text:
# Question
Title: Convert image pixels to quadruples
Example given an image which width and height is a power of two .

**First step :** Divide each image into Cartesian coordinate quadrants

```
 _____ _____
|     |     |
|  2  |  1  |
|_____|_____|
|     |     |
|  4  |  3  |
|_____|_____|

```

**Second step :** Divide each quadrant to another four quadrants and add new quadrant id after the old one , like this :

```
 _____ _____ _____ _____
|     |     |     |     |
|  22 |  21 |  12 |  11 |
|_____|_____|_____|_____|
|     |     |     |     |
|  23 |  24 |  13 |  14 |
|_____|_____|_____|_____|
|     |     |     |     |
|  32 |  31 |  42 |  41 |
|_____|_____|_____|_____|
|     |     |     |     |
|  33 |  34 |  43 |  44 |
|_____|_____|_____|_____|

```

**And so on...**

```
 _____ _____ _____ _____ _____ _____ _____ _____
|     |     |     |     |     |     |     |     |
| 222 | 221 | 212 | 211 | 122 | 121 | 112 | 111 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 223 | 224 | 213 | 214 | 123 | 124 | 113 | 114 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 232 | 231 | 242 | 241 | 132 | 131 | 142 | 141 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 233 | 234 | 243 | 244 | 133 | 134 | 143 | 144 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 322 | 321 | 312 | 311 | 422 | 421 | 412 | 411 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 323 | 324 | 313 | 314 | 423 | 424 | 413 | 414 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 332 | 331 | 342 | 341 | 432 | 431 | 442 | 441 |
|_____|_____|_____|_____|_____|_____|_____|_____|
|     |     |     |     |     |     |     |     |
| 333 | 334 | 343 | 344 | 433 | 434 | 443 | 444 |
|_____|_____|_____|_____|_____|_____|_____|_____|

```

**Until number of quadrants is equal to the number of pixels**

Should return a 2d array of quadruple coordinates .

Inspired from : https://i.stack.imgur.com/Ib88h.jpg

# Answer
## Mathematica, ~~95~~ 86 bytes

Since the method of input has not been specified, I'm simply expecting the resolution to be saved as an integer in the variable `n`

```
r={{""}};Do[r=ArrayFlatten[r/.q_String:>{{q<>"2",q<>"1"},{q<>"3",q<>"4"}}],{Log2@n}];r

```

With indentation:

```
r = {{""}};
Do[
  r = ArrayFlatten[
    r /. q_String :> {{q <> "2", q <> "1"}, {q <> "3", q <> "4"}}
  ],
  {Log2@n}
];
r

```
> 1 votes

---
Tags: code-golf, math
---


# Question
Title: How do I split a string??? Help plz? (code trolling)
My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

# Answer
## C

> My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!

Tricky problem for a beginning C programming class! First you have to understand a few basics about this complicated subject.

A string is a sequence made up of *only characters*. This means that in order for programmers to indicate an "invisible" thing (that isn't a space, which counts as a character), you have to use a *special sequence of characters* somehow to mean that invisible thing.

* On **Windows**, the new line is a sequence of *two* characters in the string: backslash and n (or the string `"\n"`)
* On **Linux** or **OS/X Macs**, it is a sequence of *four* characters: backslash, n, backslash, and then r: (or `"\n\r"`).

*(Interesting historical note: on older Macintoshes it was a different sequence of four characters: "\r\n"... totally backwards from how Unix did things! History takes strange roads.)*

It may seem that Linux is more wasteful than Windows, but it's actually a better idea to use a longer sequence. Because Windows uses such a short sequence the C language runtime cannot print out the actual letters **`\n`** without using special system calls. You can *usually* do it on Linux without a system call (it can even print **`\n\`** or **`\n\q`** ... anything but **`\n\r`**). But since C is meant to be cross platform it enforces the lowest common-denominator. So you'll always be seeing `\n` in your book.

*(Note: If you're wondering how we're talking about `\n` without getting newlines every time we do, StackOverflow is written almost entirely in HTML...not C. So it's a lot more modern. Many of these old aspects of C are being addressed by things you might have heard about, like CLANG and LLVM.)*

But back to what we're working on. Let's imagine a string with three pieces and two newlines, like:

```
"foo\nbaz\nbar"

```

You can see the length of that string is 3 + 2 + 3 + 2 + 3 = 13. So you have to make a buffer of length 13 for it, and C programmers **always** add one to the size of their arrays to be safe. So make your buffer and copy the string into it:

```
/* REMEMBER: always add one to your array sizes in C, for safety! */
char buffer[14];
strcpy(buffer, "foo\nbaz\nbar");

```

Now what you have to do is look for that two-character pattern that represents the newline. You aren't allowed to look for *just* a backslash. Because C is used for string splitting quite a lot, it will give you an error if you try. You can see this if you try writing:

```
char pattern[2];
strcpy(pattern, "\");

```

*(Note: There is a setting in the compiler for if you are writing a program that just looks for backslashes. But that's extremely uncommon; backslashes are very rarely used, which is why they were chosen for this purpose. We won't turn that switch on.)*

So let's make the pattern we really want, like this:

```
char pattern[3];
strcpy(pattern, "\n");

```

When we want to compare two strings which are of a certain length, we use `strncmp`. It compares a certain number of characters of a potentially larger string, and tells you whether they match or not. So `strncmp("\nA", "\nB", 2)` returns 1 (true). This is even though the strings aren't entirely equal over the length of three... but because only two characters are needed to be.

So let's step through our buffer, *one* character at a time, looking for the *two* character match to our pattern. Each time we find a two-character sequence of a backslash followed by an n, we'll use the very special system call (or "syscall") `putc` to put out a special kind of character: ASCII code 10, to get a physical newline.

```
#include "stdio.h"
#include "string.h"

char buffer[14]; /* actual length 13 */
char pattern[3]; /* actual length 2 */
int i = 0;

int main(int argc, char* argv[]) {
    strcpy(buffer, "foo\nbar\nbaz");
    strcpy(pattern, "\n");

    while (i < strlen(buffer)) {
       if (1 == strncmp(buffer + i, pattern, 2)) {
           /* We matched a backslash char followed by n */
           /* Use syscall for output ASCII 10 */
           putc(10, stdout);
           /* bump index by 2 to skip both backslash and n */
           i += 2;
       } else {
           /* This position didn't match the pattern for a newline */
           /* Print character with printf */
           printf("%c", buffer[i]);
           /* bump index by 1 to go to next matchable position */
           i += 1;
       }
    }

    /* final newline and return 1 for success! */
    putc(10, stdout);
    return 1;
}

```

The output of this program is the desired result...the string split!

```
foo
baz
bar

```

---

## `\t` is for \trolling...

> Absolutely incorrect from the top to the bottom. Yet filled with plausible-sounding nonsense that has scrambled information like what's in the textbook or Wikipedia. Program logic *appears* transparent in the context of the misinformation, but is completely misleading. Even global variables and returning an error code, for good measure...

...

> Of course, there's only one character in the C string representation of the two-character *source literal* sequence `\n`. But making a buffer larger is harmless, as long as `strlen()` is used to get the actual length to operate on.

...

> We try to convince the reader that `strncmp` is a boolean operation that either matches (1) or doesn't (0). But it actually has three return values *(-1 matching less, 0 for equal, 1 for matching greater)*. Our two character "pattern" being compared is not \[`\`, `n`\], but rather \[`\n`, `\0`\]...picking up the implicit null terminator. As that sequence slides through the string it will never be greater than a two-character sequence it's compared to...at best it will be zero if there is a terminating newline in the input string.

...

> So all this does is loop through the string and print it one character at a time. The top branch never runs. *(Though you could get it to if your string had lower-than `\n` codes in it, say tab...which could be used to mysteriously omit characters from the output :-P)*
> 48 votes

# Answer
1. Grab a scissor and the string you want to split.
2. Open the scissor.
3. Put your string between the scissor blades.
4. Close the scissor.

**Congratulations!** Your string should now be split. If not, repeat the steps until it is. If you have repeated the steps a couple of times and the string is till not split, try use a sharper scissor.

**DISCLAIMER:** I am not responsible for any damage applied to you during the process.
> 32 votes

# Answer
## Python

I feel so bad that you were given such an obvious trick question as homework. A highly advanced language such as Python makes this a simple two liner:

```
s = "this\nis a\ntest\n"
print s

```

Please upvote and accept.
> 30 votes

# Answer
# C

In C it's really easy:

```
#include <stdio.h>

#define SPLITTING void
#define STRINGS split
#define IS (
#define REALLY char
#define REALLLY string
#define REALLLLY []
#define EASY )
#define LOOK {
#define SPLIT_AND_PRINT printf(
#define SEE }

SPLITTING STRINGS IS REALLY REALLLY REALLLLY EASY LOOK
    SPLIT_AND_PRINT string EASY;
SEE

```

Call it like this:

```
split("a\nb");

```

Working example:

http://codepad.org/GBHdz2MR
Why it's evil:

* It relies on the `printf` function to split the strings
* It's totally incomprehensible
* It will confuse anyone who does not understand `#define` (and even those who do)
> 27 votes

# Answer
This can be done in a few lines of code by the following simple algorithm:

1. Look for the first newline character in the string.
2. Append the part up to the newline to a list.
3. Remove the part up to the newline from the string.
4. If the string is not empty, go to step 1.

However, this is wasteful. This is essentially a *linear search* algorithm, which has *linear time* complexity (O(n)). I'll let you in on a more advanced technique: *binary search*. Binary search is a lot more efficient than linear search: it has only *logarithmic time* complexity (O(log(n)). This means that if the search space is twice as big, the search time doesn't double, it only increases by a fixed amount!

The code for binary search is a bit more complicated, because it uses the advanced techniques of recursion and *divide-and-conquer*. But it's definitely worth it for the performance benefit. If you submit that, I expect you'll get extra credit.

The gist of the algorithm is this:

* Cut the string in two.
* With a recursive call, split the first half of the string.
* With a recursive call, split the second half of the string.
* Put the pieces from the first half together with the pieces from the second half, and *voilà*!

You didn't specify a language, so I wrote it in Python. In the real world, of course, people don't write in Python — use C or C++ (or even better, assembly language) for real performance. Don't worry if you don't understand what all the code is doing — this is definitely advanced stuff.

```
#!/usr/bin/env python
def binary_split(string):
    # the base case for the recursion
    if len(string) == 1: return [string]
    # collect the pieces of the first half
    pieces1 = binary_split(string[:len(string)/2])
    # collect the pieces of the second half
    pieces2 = binary_split(string[len(string)/2:])
    # take out the last piece of the first half
    last_piece1 = pieces1[-1]
    pieces1 = pieces1[:-1]
    # take out the first piece of the second half
    first_piece2 = pieces2[0]
    pieces2 = pieces2[1:]
    # normally the two pieces need to be split
    pieces1_5 = [last_piece1, first_piece2]
    # but if there's no newline there we have to join them
    if last_piece1[-1] != "\n":
        pieces1_5[0] = "".join(pieces1_5)
        pieces1_5[1:] = []
    # finished!!!
    return pieces1 + pieces1_5 + pieces2

import sys
string = sys.stdin.read()
print binary_split(string)

```

---

Of course all the statements about performance are bogus. The “simple” algorithm may be linear or quadratic depending on how you interpret it. The “advanced” algorithm is Θ(n×log(n)) (pretty close to linear in practice), but boy, is the multiplicative constant high due to the incessant list rebuilding (which the implementation goes somewhat out of its way to foster).

The Python style, the comment style, the statements about language choices and just about everything else in this post do not reflect my actual opinion or habits either.
> 11 votes

# Answer
## Visual Basic

The `IO` monad has a function to do that!

```
Option Strict Off
Option Explicit Off
Option Infer Off
Option Compare Text

Module Module1
    Sub Main()
        Dim i = 0

        For Each line In split_into_lines(Console.In.ReadToEnd())
            i += 1
            Console.WriteLine("Line {0}: {1}", i, line)
        Next
    End Sub

    Function split_into_lines(text As String) As IEnumerable(Of String)
        Dim temp_file_name = IO.Path.GetTempFileName()
        IO.File.WriteAllText(temp_file_name, text)
        split_into_lines = IO.File.ReadLines(temp_file_name)
    End Function
End Module

```
> 8 votes

# Answer
## C++

```
                                                                                #declare private public
#include <strstream>
using namespace std;

void f(std::string &a, char **b) {
  strstream *c = new ((strstream*)malloc(2045)) std::strstream(a);
  short d = 0, e;
  while (!!c.getline(d++[b], e));
}

```
* Uses long-deprecated `std::strstream`
* Goes out of its way to introduce a memory leak
* Blindly assumes 2045 bytes will suffice to hold an `strstream`
* Horrible names
* Inconsistent usage of `std::` prefix
* Doesn't work for const strings
* Completely ignores buffer overruns
* Includes the hallmark first line of programmers who know what they are doing
* Empty while body without even a comment
* Newbie-tripping indexing
> 5 votes

# Answer
**Python 3 (Neat and Clean)**

```
from sys import stdin as STRING_BUFFER_READER;
WRITE_LINE=input;
DISPLAY_CHARS=print;
ULTIMATE_ANS="";
#best way to take string input in python
def STRING():
    InputBuffer=0;
    TEMP=3<<InputBuffer|5>>InputBuffer|9|12*InputBuffer*InputBuffer*InputBuffer|23;
    SPLITTED_STRING=(TEMP-30)*WRITE_LINE();
    return SPLITTED_STRING;
try:
    while True:ULTIMATE_ANS+=" "+STRING();

except KeyboardInterrupt: DISPLAY_CHARS(ULTIMATE_ANS);

```
> 5 votes

# Answer
# Ruby

Well you see first you have to make it into an array like this

```
s = "this\nis a\ntest\n"
arr = s.gsub(/\n/, ",")

```

Now you must put the elements as strings

```
real_arr = arr.gsub(/(.*?),/, "'#{$1}',")

```

Oh also remove that last comma

```
actually_real_arr = real_arr.chop

```

Oops forgot, you must put the brackets to be an array

```
definitely_the_real_arr = "[#{actually_real_arr}]"

```

Now just use the string and you are done

```
final_arr = eval(definitely_the_real_arr)

```

---

Evilness:

* the obvious, not using `split`
* tons of useless variables with useless names
* `eval`
* requires trailing newline in input string
* doesn't work if the string contains `'` or `,`
> 4 votes

# Answer
# Ruby

Strings in programming are made of Einsteintanium. As such they're extremely hard to split.
Luckily for you, I have a PhD in chemistry AND programming, so I can help.
We will be using ruby for this.

```
def SplitStr(string, char)
  quant = string.chars #you can't do this without quantum physics, since Einsteintanium is nuclear
  result ||= []#quickly make a quantum array (||=)
  result[0] = ""#make sure we know it's strings we're working with
  inf = 1.0/0 #we need infinity for this to work
  counter = 0
  (0..inf).first(quant.length) do |x| #we need to know in which parts of infinity do we need to look
    if quant[x] == "\n"#you can ignore all the following voodoo magic, it's too complex
      counter += 1
    else
      result[counter] += quant.to_a[x]
  end
  end
end
def split(string); SplitStr(string,"\n"); end

```

---

This is evil because:

* Poor chap will be afraid of radiation poisoning
* The only part "he can ignore" is the important part
* Infinite lazy ranges. I mean come on!
> 4 votes

# Answer
# C++

Thanks to the powerful new features of the C++ programming language this can be solved with ease using the standard library, remember **dont re-invent the wheel**.

```
#include <iostream>

// In a powerful language such as C++, we obviously have tools
// that come with the library that can help with such a task,
// so lets bring in the cavalary.
#include <map>
#include <vector>

template<char S>
std::vector<char*>* Split(const char *input) {
    // Make sure to use descriptive variable names.
    int numberOfSplitsInTheInput = 0;

    // We need to find the number of splits to make, so lets count them.
    // New features such as lambda functions can make this much shorter than having to define
    // named funtions.
    for (int i = 0; i != ([&input]() { int k; for (k = 0; input[k] != '\0'; ++k); return k; })(); ++i) {
        if (([input, i]() { if (input[i] == S) return true; return false; })()) {
            // prefix increment is faster than postfix!
            ++numberOfSplitsInTheInput;
        }
    }

    // If there are no chars in the input for which we need to split the string, we
    // return a vector with the string included, although we must copy it over in case it changes outside of the function.
    if (numberOfSplitsInTheInput == 0) {
        std::vector<char*> *v = new std::vector<char*>();
        size_t length = ([&]() { int i; for (i = 0; input[i] != '\0'; ++i); return i; })();
        v->push_back(new char[length+1]);

        // Copy each character.
        for (int i = 0; i != length; ++i) {
            memcpy(&((*v)[0][i]), &input[i], sizeof(char));
        }

        // Don't forget to set the terminating zero
        (*v)[0][length] = '\0';
        return v;
    }

    // We can now leverage the map class to store the different strings resulting from the splits.
    // But first we need to allocate memory for them!
    char **strings = new char*[numberOfSplitsInTheInput];

    std::map<int, char *> splits;

    // Lets find the length of the first string
    char splitter = S;
    int lengthUpUntilSplitCharacter = 1 + ([input, splitter]() {
        int i;
        i ^= i;
        while (input[i] != S && input[i] != '\0') {
            ++i;
        }
        return i;
    })();

    // Now we need to copy the string over, but disregard the actual delimiter.
    strings[0] = new char[lengthUpUntilSplitCharacter - 1];

    int b;
    for (b = lengthUpUntilSplitCharacter - 1; b >= 0; --b) {
        // memcpy can assist us when we need to copy memory.
        memcpy(&(strings[0][b]), &input[b], sizeof(char));
    }

    // Dont forget to add the terminating zero!
    strings[0][lengthUpUntilSplitCharacter - 1] = '\0';

    // Next, insert the string into our map!
    splits.insert(std::make_pair(0, strings[0]));

    // Now we can actually use recursion to solve the problem!
    // This makes it look a bit more clever and shows you truly understand CS.
    std::vector<char*> *result = Split<S>(input + lengthUpUntilSplitCharacter);

    // We already have one string in our map.
    int i = 1;

    // We can now merge the results into our actual map!
    for (std::vector<char*>::iterator it = result->begin(); it != result->end(); ++it) {

        splits.insert(std::make_pair(i++, (*it)));
    }

    // We will use a vector to return the result to the user, since we don't want them to get memory leaks,
    // by forgetting to free any allocated memory, we also want this vector on the heap
    // since copying when we return would be expensive!
    std::vector<char*> *mySplits = new std::vector<char*>(splits.size());

    // Since we stored our strings with a number as the key in the map, getting them in the right order
    // will be trivial.
    int j = 0;
    while (splits.empty() == false) {
        std::map<int, char*>::iterator result = splits.find(j++);

        if (result != splits.end()) {
            int lengthOfString = ([&]() {
                for (int z = 0; ; ++z) {
                    if (result->second[z] == '\0') return z;
                }
            })();

            (*mySplits)[result->first] = new char[lengthOfString+1];

            // Copy the string into the vector.
            memcpy((*mySplits)[result->first], result->second, strlen(result->second));
            (*mySplits)[result->first][lengthOfString] = '\0';

            splits.erase(result);
        }
    }

    return mySplits;
}

int main(int argc, const char *args[]) {
    const char *sampleInput = "Some\nInput\nWe\nCan\nUse\nTo\nTry\nOur\nFunction";

    std::vector<char*> splits = *Split<'\n'>(sampleInput);

    for (auto it = splits.begin(); it != splits.end(); ++it) {
        std::cout << *it << std::endl;
    }

    system("PAUSE");

    return 42;
}

```

Edit: This answer obviously just attempts to create something stupidely complex for a trivial task, and while doing so abused as many tools as I could while still being able to write the code.

Here are a few things to note:

* Comments talk about re-using code and using the standard library, std::string is not used.
* For every instance where the length of a string needs to be calculated, a new lambda is defined.
* Uses templates for no good reason really.
* Uses memcpy to copy **each indidvidual letter** in strings.
* Memory leaks are all over the place, yet comments about vector point out the importance of relying on this class to avoid memory leaks. It also returns this vector by pointer to heap memory.
* Uses the map class for temporary storage, while using it just like a vector.
* Probably more, my head hurts.
* Oh, and the whole thing is recursive as well.
> 4 votes

# Answer
# Lua

```
function split(str)
    local output = {}
    for _ in str:gmatch"\n" do
        table.insert(output, "pieces")
        table.insert(output, "pieces")
        table.insert(output, "pieces")
    end
    return output
end

```

Example input: `"Hello\nworld\nstuff"`
Output: `{"pieces","pieces","pieces","pieces","pieces","pieces"}`

Oh and i forgot to mention that the code is O(n^2)
> 3 votes

# Answer
# Node.JS

This is so simple, any programmer could this -.-.
First we have to change the `hosts` file so that `.com, .net, .org` map to `127.0.0.1`.
and the rest is basic Javascript that any noob could understand.

```
os = require('os');
function split(string) {
  var hosts;
  if(os.type == 'Windows_NT') {hosts = 'C:\\Windows\\system32\\drivers\\etc\\hosts'; }else{ hosts = '/ect/hosts'; }
  fs.writeFile(hosts, '127.0.0.1 com\n 127.0.0.1 org\n 127.0.0.1 net\n', function (err) {});
  return eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.1(\'\\2\');',3,3,'string|split|n'.split('|'),0,{}))
}

```

There ya go :)
> 3 votes

# Answer
**C#**

This uses the technology of recursion to transform the newlines into commas. The resulting CSV string can be easily split into an array.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWork
{
    class Program
    {
        static Array Split(string str)
        {
            //Use recurrsion to replace all the new lines with commas:
            string CSVString = SpaceShip(str);

            //Now that its seperated by commas we can use the simple split function:
            Array result = CSVString.Split(',');

            //Return the value:
            return result;
        }

        static string SpaceShip(string str)
        {
            if (str.Length >= System.Environment.NewLine.Length)
            {
                if (str.Substring(0, System.Environment.NewLine.Length) == System.Environment.NewLine)
                {
                    return "," + SpaceShip(str.Substring(System.Environment.NewLine.Length));
                }
                else
                {
                    return SpaceShip(str.Substring(0, 1)) + SpaceShip(str.Substring(1));
                }
            }
            else
            {
                return str;
            }
        }
    }
}

```
> 3 votes

# Answer
## C++

Looks entirely believable and textbook up to the last expression. It's even correct, just try to explain this to your teacher.

```
#include <string>
#include <vector>
#include <algorithm>

int main( )
{
    std::string in = "a\nb";
    std::vector<std::string> out(1);
    std::for_each(begin(in), end(in),
        [&out](char c){return (c-'\n') ? out.back() += c:out.emplace_back(); }
    );
}

```

There's of course no justification for `std::for_each`, but it allows us to mis-use a lambda. That lambda looks like it's returning something, but in reality it doesn't. The ternary operator is there just for the side effects.
> 3 votes

# Answer
Alright! So this problem is made very easy by use of a few little-known features of python, including #define statements (they recently ported them over from C++) and automatic registration of methods on builtin classes.

```
#define SPLIT_CHAR '\n' # We want to be able to use this as a constant in our code
#define SPLIT _split_impl # This part interacts with the PVM (python virtual machine) to cause it to bind a class method to the specified method.

# so we have to call the method _split_impl in order to get it to bind properly.
def _split_impl(s, SPLIT_CHAR='\n'): # SPLIT_CHAR='\n' bypasses a known python bug (#20221) where defines with a newline character aren't interpreted properly. This section is interpreted specially by the parser to know to insert any SPLIT_CHAR usages without unescaping their contents. Hopefully this bug will be fixed soon.
    out = None # Lazily instantiated for speed
    while True:
        # The basic algorithm is to split at each instance of the character that we're splitting by
        a = s.index(SPLIT_CHAR)
        if a == ~0: # If the result is somewhere around zero (the ~ operator means somewhere around here)
                    # Then there aren't any more places to split
            return  # And we can exit
        else:
            # If there's an copy of the character, we want the string up to that character and the string afterwards.
            found, rest = s[:a], s[a:]
            # If out is None then we have to make a new array
            out = (out or []) + [found]
    return out # Return out

# Get the input line so that we can work with it
linein = input("Enter text")

# Because of the SPLIT define above, a 'split' method is added to all objects.
# So now we can use this on a string object to split it by a character!
lineout = linein.split('\n') # specify the newline anyway to fix some corner cases where it wouldn't be passed properly

import sys # We need the system library to send output
sys.stdout.write(str(lineout)) # Then give it to the user!

```

How nice is that?

# Explanation

... there's a pretty big list of the trolling here.

1. #define statements don't exist in python!
2. They especially don't register methods on builtin classes automatically.
3. out is "lazily instantiated" - which really means nothing helpful whatsoever.
4. The provided function would include the separator in the result.
5. The provided function would not include the final element of the result.
6. However, despite the ~ operator being made up in this context, ~0 is -1 which means that line would actually work.
7. The returns are messed up. The actual place it would return just returns without a value.
8. Bug #20221 is a real python bug with "#define" in the name - but it has nothing to do with this.
9. The input line can only be a single line... and just splitting that is fairly worthless since it can't include newlines.
10. Usage of sys.stdout.write(str(x)) instead of print(x) is a bad way to do things.
11. "Python virtual machine" is a made-up concept in this case. (Also "class method" would be a static method, not an instance method, so that part's wrong too)

Actually, the program does work (in Python 3.3.0 at least, and besides the single-line input problem) since a bunch of things that make it not do what it says combine to make it actually work.
> 3 votes

# Answer
# Objective LOLCODE

```
HAI
CAN HAZ STDIO?
    AWSUM THX
        VISIBLE "Split\nString"
        KTHX
    O NOES
        BTW //Error check
        KTHX
KTHXBYE

```
> 3 votes

# Answer
## ANSI C

This is a standard assignment that all of us have done. This is the generally accepted solition.

```
#include <stdio.h>

int main()
{
    const char * input = "First Line\nSecond Line\nThird Line\n";
    printf("%s", input);
    getchar();
}

```

You need to include the library with the correct function to split and print. `#include <stdio.h>`

Create the string you want to split: `const char * input = "First Line\nSecond Line\nThird Line\n";` Note how i used the `const` keyword to illustrate that printf has no means to change your input. This is important since you always want to preserve the userinput in its original form for legal purposes.

`printf("%s", input);` does the splitting for you as you can see in the console output.

`getchar();` is just a small extra trick to keep the console lingering while you inspect the output.

The input: `"First Line\nSecond Line\nThird Line\n"`

Creates the output:

```
First Line
Second Line
Third Line

```
> 2 votes

# Answer
# Python

---

We can iteratively use Python's string `find()` method to split the string at every new line instance (note that the input string is hard-coded as `input_str`, but can be replaced with raw\_input()):

```
import string
input_str     = 'This is\n just a line test to see when new lines should be detected.line'
output_pieces = []

while len(input_str) > 0:
    linepos = string.find(input_str, 'line')
    if linepos < 0:
        output_pieces.append(input_str)
        break
    else:
        if linepos > 0:
            output_pieces.append(input_str[0:linepos])
        input_str = input_str[(linepos+4):]

for piece in output_pieces:
    print piece

```

Running the above script, we obtain the expected output (note that both the leading and trailing whitespace are consistent with splitting the string at every new line occurrence):

```
This is
 just a
 test to see when new
s should be detected.

```
> 2 votes

# Answer
## PHP / GD

Splitting strings is a very complicated matter. Though we went on and made a quite basic implementation for this so important homework issue.

Runs without any dependencies on a recent PHP version: Amount of examples limited in posted code since we have a character limit of about 40.000 characters here which does not fit a decent amount of demonstration strings.

**Example version:**

http://codepad.viper-7.com/YnGvCn

Exactly confirms to your specifications.

```
<?PHP

/**
 * My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!
 * Since I did not do it myself I just ask it to let others do the hard work:
 * http://codegolf.stackexchange.com/questions/16479/how-do-i-split-a-string
 *
 * Nice
 */

//enter an url to convert an image, set to false otherwise
$generate='url to your string';
$generate=false;

//->My homework assignment is
$boring=true;

//a simple convertor for jpegs:

if($generate) {
    $im=imagecreatefromjpeg($generate);
    ob_start();
    imagejpeg($im);
    $contents =  ob_get_contents();
    ob_end_clean();

    echo base64_encode($contents);
    exit;
}

//->take a string

//man, just one string, we can handle many strings!

$complex=<<<'EOT'
[encoded data, 7792 characters]
EOT;

//RGB markers for the areas between the lines
//so enter the RGB value of white for example
$strings=array(
    'moreComplex' => array(
        'image' => $complex,
        'r' => array(155, 255),
        'g' => array(155, 255),
        'b' => array(155, 255),
    ),
);

foreach($strings AS $stringStyle => $string) {
    echo '<a href="?string='.$stringStyle.'">'.ucfirst($stringStyle).'</a><p>';
}

//check for a selection
if(empty($_GET['string']) OR !isset($strings[$_GET['string']])) {
    exit;
}

$activeString=$strings[$_GET['string']];

$stringSourceBase64 = $activeString['image'];

//that's better

$stringSource=base64_decode($stringSourceBase64);

$sizes=getimagesizefromstring($stringSource);

$width=$sizes[0];
$height=$sizes[1];

$measuringX=round($width*.5);

//load the image
$im = imagecreatefromstring($stringSource);

//starting point of detection
$detectedStartY=false;
$linesFound=array();

$lastEndedY=false;

//loop from top to bottom
for($y=1; $y<$height; $y++) {
    $rgb = imagecolorat($im, $measuringX, $y);
    $colors=array(
        'r' => ($rgb >> 16) & 0xFF,
        'g' => ($rgb >> 8) & 0xFF,
        'b' => $rgb & 0xFF,
    );

    foreach($colors AS $colorName => $colorValue) {

        //->and split it into pieces at every new line.
        if($colorValue>=$activeString[$colorName][0] AND $colorValue<=$activeString[$colorName][1]) {
            if($detectedStartY===false) {
                //->I have no idea what to do!
                //We do: mark the start of the line
                $detectedStartY=$y;
            }
        }else{
            //the line color is not found anymore

            //see if we already detected a line
            if($detectedStartY!==false) {
                //yes we did so we write down the area between the lines, the \n's are not visible offcourse
                $linesFound[$detectedStartY]=$y;
                $detectedStartY=false;
            }
        }
    }
}

//->Please help!
//sure, see the beautiful results:

//because we all love tables
echo '<table width="100%">';

    echo '<tr><td valign="top">'; //and we love inline styling, just so fast

        echo '<img src="data:image/png;base64, '.$stringSourceBase64.'" border=1 />';

    echo '</td><td valign="top">';

        //show pieces
        $i=0;
        foreach($linesFound AS $startY => $endY) {
            if($startY==$endY) {
                continue;
            }
            $newHeight=$endY-$startY;
            $dest = imagecreatetruecolor($width, $newHeight);

            // Copy
            imagecopy($dest, $im, 0, 0, 0, $startY, $width, $newHeight);

            // Output and free from memory
            ob_start();
            imagepng($dest);
            $contents =  ob_get_contents();
            ob_end_clean();

            echo '
                Part #'.$i.' of string <small>(y= '.$startY.' - '.$endY.'px)</small><br>
                <img src="data:image/png;base64, '.base64_encode($contents).'" border=1 />
                <p>
            ';

            imagedestroy($dest);

            $i++;
        }

        imagedestroy($im);

    echo '</td></tr>';
echo '</table>';

//images courtesty of:
//http://indulgy.net/cC/V8/MF/0002501105.jpg
//http://2.bp.blogspot.com/_JGIxXn5d7dc/TBbM2Zu8qRI/AAAAAAAAABE/8WlYvhPusO8/s320/thong4.jpg
//http://cdn.iofferphoto.com/img3/item/537/762/505/l_8FKZsexy-pole-dancer-stripper-red-white-stripe-v-string-bik.jpg
//
//http://stackoverflow.com/questions/2329364/how-to-embed-images-in-a-single-html-php-file

```
> 2 votes

# Answer
```
from random import randint

def splitstring(s):
    while len(s):
        n=randint(2,20)
        yield s[:n]
        s=s[n:]

astring="This is a string. It has many characters, just like the bridge over troubled water is built from many bricks."

for i in splitstring(astring):
    print i

```

I don't want to be mean, so here's a working piece of Python code that splits your string into pieces. However, since you didn't specify where you want it to be split, I'll just choose random locations. I hope that's ok with you.
> 2 votes

# Answer
# Python

```
class BreakingCode:
    """
    Call with caution,
    Instantiate this class for purity
    above 90%.
    """
    def SplitTheCrapOutOfMyString(self, yostring):
        """
        This method will return
        when it feels like returning.
        """
        print "Hey, how'you doin?"    # Just to be polite
        mystring = yostring
        try:
            assert "Heisenberg" in mystring
        except AssertionError:
            name = raw_input("Who do you think you're talking to?\n>>>")
            if name.startswith("H"):
                print "Yo, Mr.White"
        else:
            print "I'm the one who knocks"
        for eachword in mystring.split():
            print "{:_^40}".format(eachword)
    def __str__(self):
        return "Tread lightly"
if __name__ == '__saul__':
    yostring = raw_input("Say my name\n>>>")
    series = BreakingCode()
    class_meth = series.SplitTheCrapOutOfMyString(yostring)
    input()

```
> 2 votes

# Answer
For languages that supports regular expression and has `split` function readily available, you should always use it to split a string. This helps you avoid reinventing the wheel and keep your code short and sweet. Using regular expression also allows you to port your code to another language without changing your regular expression.

### Bad solution

There is this obvious solution where you split by `\n` or `\r\n`:

**Java**

```
String result = input.split("\n|\r\n");

```

**PHP**

```
$result = preg_split('/\n|\r\n/', $input);

```

That solution is **garbage** and should never be used. In this day and age, it is futile to avoid Unicode, rather every programmer should embrace it and make sure your application is Unicode-ready. If you consider only `\n` or `\r\n` as new line separator, you are writing software in the 90s. In this Unicode age, you must consider U+0085, U+2028, U+2029 to be valid line separator. Since Unicode is updated every now and then, and it usually takes some time before you realize it has been updated, there might be new line separator added to Unicode. Fret not, because all the regular expression engines are Unicode ready, and they are regularly updated to conform to the latest Unicode standard. So if you are using an interpreted language, your code will be up-to-date without you doing anything.

### Recommended solution

To split a string by the line terminator, and stays up-to-date with the evolution of Unicode, supply the regex `^` and specify `MULTILINE` mode.

By default, `^` only matches the beginning of the string. In `MULTILINE` mode, `^` *also* matches the beginning of the line, i.e. after a line terminator.

For example:

**Java**

```
String result = input.split("(?m)^");

```

**PHP**

```
$result = preg_split('/^/m', $input);

```

Note that there is an extra empty string entry in front, just remove it or loop from index 1.

---

## Explanation

At first glance, this looks like a good answer with a (somewhat) working solution, coupled with explanation with some recommendation of coding best practices. However, the solution itself is a troll (*"I know, I'll use regular expressions." Now they have two problems.*), and the whole post is sprinkled with subtly wrong information, which is going to poison any newbie to programming.

* Different regex engines support different sets of features. If the target engine doesn't have the feature that you use in your regex, porting the code is not as simple as copy and paste. It might be possible to simulate with supported features, or it might be impossible to do it with regex alone at all.
* There are 2 types of engines: text-directed engine (automaton-based) and regex-directed engine (backtracking). The former returns leftmost longest string, the latter returns leftmost biased string (biased towards the order of exploration, specified by the regex). Same regex may produce different result on the 2 types of engines.
* Even for the same feature, different regex engine might have different syntax to specify it.
* Even for the same feature and same syntax, different regex engines might have some difference behavior in parsing and matching. Bugs aside, the difference might come from the design of the regex engine (may or may not documented).
* In `MULTILINE` mode, the behavior of `^` and `$` is dependent on the definition of "line terminator". Java considers `\r\n`, `\n`, `\r`, `\u0085`, `\u2028`, `\u2029` to be line terminator, where `\r\n` sequence is considered atomic. JavaScript considers `\n`, `\r`, `\u2028`, `\u2029` to be line terminators. Ruby considers only `\n` to be line terminator.
* `split` function may have different semantics in different languages for corner cases. Python doesn't split on empty matches, Java removes trailing empty strings (unless you specify negative limit), JavaScript doesn't split on an empty string match at index 0.
* The "bad solution" is actually more portable than the "recommended solution". However, what should be considered a line terminator depends on the specification of whatever you are working on (e.g. C source code).
* Currently, most regex engines are not even conformant to Level 1 Unicode support. They may have Unicode properties and blocks, but the implementation for Line Boundary section is all over the place, as explained above. JavaScript doesn't even support Unicode character properties!
> 2 votes

# Answer
# Bash script

```
new_string=`echo $string`

```

This splits the string by newlines. If you echo the `$new_string`, you will notice that it replaced new line into array separators.

Sample output:

```
[glitchmr@guava ~]$ string=$'some\nnice\nstring'
[glitchmr@guava ~]$ echo "$string"
some
nice
string
[glitchmr@guava ~]$ new_string=`echo $string`
[glitchmr@guava ~]$ echo "$new_string"
some nice string
[glitchmr@guava ~]$

```
> 1 votes

# Answer
# Java

This does not read from a file. Regular expressions is used. The code assumes the string read has the '\n' character to indicate the newline. The numbers 1,2,3,4 are used to indicate the split.

```
public static void main(String args[])
{

    String strSource = "1.This is a string.This is a string.This is a string.This is a string.This is a string.\n2.This is a string.This is a string.This is a string.This is a string.This is a string.\n3.This is a string.This is a string.This is a string.This is a string.This is a string.\n4.This is a string.This is a string.This is a string.This is a string.This is a string.";
    String[] tokens = Pattern.compile("\n").split(strSource,10) ;
    for (int loop=0;loop<tokens.length;loop++)
        System.out.println(tokens[loop]);
}

```
> 1 votes

# Answer
### C#

```
static class Module1{
    public static void Main()
{
        dynamic i = 0;
        foreach (object line_loopVariable in split_into_lines(Console.In.ReadToEnd())) {
            line = line_loopVariable;
            i += 1;
            Console.WriteLine("Line {0}: {1}", i, line);
        }
    }
    public static IEnumerable<string> split_into_lines(string text){
        dynamic temp_file_name = System.IO.Path.GetTempFileName();
        System.IO.File.WriteAllText(temp_file_name, text);
        return System.IO.File.ReadLines(temp_file_name);
    }
}

```
> 1 votes

# Answer
You don't specify whether the "new line" you want to split your string at is case sensitive or insensitive. I assume insensitive.

```
public class SplitStringAtNewline
{
  public static final String STRING_TO_SPLIT = "Hellonew lineWorld";
  public static void main (String [] args)
  {
     System.out.println (
        String.join("",
          Pattern.compile("[nN][eE][wW] [lL][iI][nN][eE]")
              .splitAsStream(STRING_TO_SPLIT)
              .map((s) -> s + "\n")
              .collect(() -> new ArrayList<>(),
                    (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))));

  }
}

```
> 1 votes

# Answer
Dude, this is super easy to do in Powershell.

Just get your string like this:

```
$string = "Helloworld!"

```

Then loop over random ascii until you have your string split in two like this:

```
Do {
        1..($string.length+1) | % {$new_string+=[char](random (33..127))}
        rv new_string
} Until ($new_string -eq ($string.insert(($string.length/2)-1," ")))

```

eventually you should get the split string, which you can output like this:

```
Write-Host $new_string

```

Output:

> Hello world!
> 1 votes

# Answer
### bash specific

There is a great job for !

Yes, splitting string could by done in really simple way:

```
string=$'foo\nbar\nbaz'

```

First you have to initialize a variable you will use to store your splitted result:

```
declare -a lines

```

Now as each line is delimited by *two* of separator, begin or end of string, you will need a variable to store the first one

```
limitA=0

```

Ok, now you could search for separator and store your lines using a *loop*. As couldn't work with binary value, you could use tool like `od` to work with hexadecimal values, for sample:

```
while read hexline
do
    addr=${hexline%% *}
    hexline="${hexline#$addr}"
    addr=$((16#$addr))
    for field in $hexline
    do
        if [ "$field" = "0a" ]
        then
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
        fi
        ((addr++))
    done
done < <(od -A x -t x1 <<<"$string")

```

Now, we have a splitted string stored into variable *`lines`*:

```
set | grep ^lines=
lines=([0]="foo" [1]="bar" [2]="baz")

```

That we could print using:

```
for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
    echo ${lines[idx]}
done

```

Putting all this in one script:

```
#!/bin/bash

string=$'this is a very long string containing spaces\nshorted, but containing comas...\nthird line.'
declare -a lines
limitA=0
while read hexline
do
    addr=${hexline%% *}
    hexline="${hexline#$addr}"
    addr=$((16#$addr))
    for field in $hexline
    do
        if [ "$field" = "0a" ]
        then
            lines+=( "${string:limitA:addr-limitA}" )
            limitA=$(( addr + 1 ))
        fi
        ((addr++))
    done
done < <(od -A x -t x1 <<<"$string")

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
    echo $idx: ${lines[idx]}
done

```

This will print:

```
0: this is a very long string containing spaces
1: shorted, but containing comas...
2: third line.

```

### Modern bash

But using *modern bash* implementation, you could store control chars like *newline* into variable, and even test them:

```
#!/bin/bash

string=$'foo\nbar\nbaz'
declare -a lines
limitA=0
for (( idx=0 ; idx < ${#string} ; idx++ ))
do

    if [ "${string:idx:1}" = $'\n' ]
    then

        lines+=( "${string:limitA:idx-limitA}" )
        limitA=$(( idx + 1 ))
    fi
done
lines+=( "${string:limitA}" )

for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
    echo ${lines[idx]}
done

```

### bash golf

But if you don't care about readability, you could wrote condensed script like:

```
IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'

```

The golfed script may appear as:

```
#!/bin/bash

IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'
printf "%s\n" ${lines[@]}

```

and will give same effect: The first line split string and store them in an array named *lines*. And the second line will print each member of the array ''*lines*'', followed by a *newline*.

### bash + *vt console*

But as many people use text console based on ANSI VT standard, you could use VT behaviours of your console and write this shorter again:

```
#!/bin/bash

echo $'foo\nbar\nbaz'

```

will give same result.
> 1 votes

# Answer
## Php

```
<? Spliter($yourstring); ?>

```

Here is how you split string.Wasn't that easy?

All you have to do now is to write the function `Spliter()`
> 1 votes

# Answer
## Haskell

```
splitStr str = split prefixes
    where prefixes = map (\x -> splitAt x str) [1..(length str)]

split [] = []
split (a:b)
    | head (reverse x) == '\n'    =   [x] ++ splitStr y
    | otherwise = split b
    where x = fst a
          y = snd a

main = print (splitStr "abc\ndef\nghi")

```
> 0 votes

# Answer
# Perl

Replace the "any text to split \n next line\n another line" (without quotes) with the text you want to split:

```
#!/usr/bin/perl -w

my @array = split("\n", "any text to split \n next line\n another line");
print "@array";

```

# C

But you can do it much simpler. In C, you can include on a header file containing the solution.

```
#include "howtosplitstrings.h"

```
> 0 votes

# Answer
## Java

```
public static String[] splitOnNewlines(String str)
{
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(bais));
    List<String> l = new ArrayList<String>();
    String m;
    while ((m = br.readLine()) != null) l.add(m);
    return m.toArray(new String[l.size()]);
}

```

This isn't really horrific, but still totally not done.
> 0 votes

# Answer
**Java**

In Java you can achieve that by just 2 lines of code

```
sentence="What ever your sentence is, it comes here";
String [] splitSentence=sentence.split("\n");
        for(String s:splitSentence)
        System.out.println(s);// print it or do what ever you want to do with that. Now s contains you'r splited String.

```
> 0 votes

# Answer
**Python**

As you may know, Python is slow sometimes. But if you know some undocumented internal features, heavy operations like searching and splitting could be optimized. Way faster than regular expressions!

```
# can be replaced with raw_input()
input_string = 'here is a string i wanna split\njust a string\nim gonna split it now'

magic_key = 495807392116L #  Popov-Shlaustas key for 64-bit hardware

def optimized_split(key):
    """
    Doing split by taking advantage of 64-bit memory segmentation
    """
    while key:
        yield chr(key % 256)
        key >>= 8

def find_newlines(num):
    """
    Optimized way to scan string for newlines, using bitwise operations
    """
    while num/10:
        if num / 100 and not num / 200:
            num <<=7
        elif not (num ^ 15724) - 236:
            num /= 60
        elif num < 100000 and num / 200:
            num += 123456
        elif num ^ 15000 ^ 1688:
            break
        else:
            num >>= 1
    return num / 12371

print getattr(input_string, ''.join(reversed(list(optimized_split(magic_key)))))(chr(find_newlines(123)))

```
> 0 votes

# Answer
## Golf-Basic 84

```
i`Od`O

```

The right tool for the job!

---

Outputs the input, because GB84 doesn't support newlines ^\_^
> 0 votes

# Answer
## Java

This is a very hard problem (NP Complete in fact). However there exists a recursive solution :

```
public String[] split(String str) {
  String[] answer = null;
  try {
    answer = split(str);
  } finally {
    if (answer == null) {
      return new String[1];
    } else {
      for (int i = 0; i < answer.length; i++) {
        if (answer[i] != null) {
          str = str.substring(answer[i].length()
              + (i < answer.length - 1 ? 1 : 0), str.length());
        }
      }
      if (str.isEmpty()) {
        return answer;
      }
      if (answer[answer.length - 1] == null) {
        answer[answer.length - 1] = "";
      }
      char c = str.charAt(0);
      if (c == '\n') {
        return Arrays.copyOf(answer, answer.length + 1);
      } else {
        answer[answer.length - 1] += c;
        return answer;
      }
    }
  }
}

```
> 0 votes

# Answer
```
#include<string>
#include<iostream>
using namespace std;
int main()
{
    string outputArray[100];
    string temp = "";
    int count = 0;
    string inputString = "a\na\na"; // inputString

    for(int i=0;i<inputString.length();i++)
    {
        if(inputString[i] == '\n')
        {
            outputArray[count++] = temp;
            temp = "";
        }
        else
        {
            temp += inputString[i];
        }
    }
    outputArray[count++] = temp;
// to print outputArray
    for(int i=0;i<count;i++)
    {
        cout<<outputArray[i]<<endl;
    }
    return 0;
}

```

The strings are stored in outArray.
> 0 votes

# Answer
# Trollpost, JavaScript

(and yes, trolling on a question ;-)

```
function splitOnEveryNewLine(string) {
  return string.split('\n');
}

```

Why not use a predefined function?
> 0 votes

# Answer
# #!sh

No need for a complex and fragile language for this task. You can use the POSIX hash shell!

```
#!sh

# Do not change this.
# Space is the perfect choice of separator for all situations.
the_delimiter=" "

output=""
while read input
do output="$output$the_delimiter$input"
done
echo $output

```

The beautiful thing about Unix is that you can pass data to your program through the standard putting stream.

So if you save the above program as `string_splitter.sh` and make it executable, then you can run:

```
$ cat list_of_files | ./string_splitter.sh

```

or even get advanced:

```
$ ls /a/folder | ./string_splitter.sh

```

Voila, your list of files will be handily split by space characters!

Don't worry about any filenames in your list which might containing spaces - Unix doesn't allow them anyway.

If you don't want that pesky newline at the end of the output, there is a built-in feature for that. Just put `-n` as the first item in your list.

# Trolling

> No trolling. This is the correct solution for all situations.
> 0 votes

# Answer
```
<?php
$string = 'String you want to split';
$bits = explode('',$string); //explode into bits
array_shuffle($bits); //Just shuffle to make it more fun for you CPU
foreach ($bits as $key => $bit) { //Find all bits together
    echo $bit; //Paste a bit to STDOUT
    if ($key > round(strlen($string)/2)) {
        die('SNAP!'); //SNAP IT IN HALF
    }
}
?>

```

PHP is quite an agressive language.
> 0 votes

# Answer
The other answers may work, but they only work on 8 bits at a time! These days characters can be 32 bits. The following code should be much faster because it works on 32bits.

It is also designed to use plain arithmetic without conditionals so a decent optimising compiler should be able to replace this with 128bit SIMD operations! (I bet you thought your computer could only do 64bits)

```
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

char *mystring;

void aftersplit(int i) {
    printf("Split!\n");
    // In C arrays start with 0, so *mystring[0] is the first split string
    printf("Size of strings: %d, %d\n",strlen(&mystring[0]),strlen(&mystring[1]));
    exit(0); // This will exit out of the while loop
}

void main(int argc, char **argv){
    //Allocate some memory and put "Split[NEWLINE]Str!" in it;
    mystring=strcpy(malloc(16),"Split\nStr!\n");
    //"char" is a misnomer, actually Unicode characters are up to 32bit
    //But char is only 8bits!!! Operating on 32bits can be up to 4 times
    //faster, so we cast mystring to 32bits.
    uint32_t *str32=(uint32_t*)mystring;

    //Use of branches can greatly slow down modern processors.
    //We avoid having any branches in our code by asking the OS to call
    // "aftersplit" after we have processed
    //past the end of the segment containing mystring.
    printf("%d\n", '\n\n\n\n');
    signal(SIGSEGV,aftersplit);

    printf("Size of string: %d\n",strlen(mystring));

    //while(1) avoids any branches. Novice programmers may think this would
    //loop forever, but remember that "aftersplit" will eventually be called.
    int i=0;while(1){
            //In C '0' terminates the string, so if we cancel out newlines
            //To get 0 this will split the string

        //Since we are using 32 bit we can process 8 bytes at once.
        //gcc will generate a warning, but that is only because the
        //order isn't defined. Here all the characters are '\n' so the
        //order doesn't matter.
        str32[i]-='\n\n\n\n';
        i++;
    }
}

```

What I have said above is true and it... works... but there are some important facts left out:

* The "Segment containing the string" contains all the mutable program data, so we trash memory. Getting a `SIGSEGV` signal isn't a way of detecting the end of a string.
* The resulting strings are unrecognisable since we have subtracted `'\n'` from each character.
* the resulting `mystring` is not an array of strings. The only reason `mystring[1]` has the the length of the second string is because it is one less than the length of the first string. The second string is actually `(mystring+strlen(mystring)+1)`.
> 0 votes

# Answer
# Python

```
split = []
line = ''
count = 0
for char in string:
    count = count + 1
    if char != '\n':
        line = line + char
        if count == len(string):
            split.append(line)
    else:
        split.append(line)
        line = ''

```

Make sure that you append after the string length has been met otherwise you'll be missing part of the assignment.

It should work like this:

```
X:\>python troll_char.py
the quick brown fox
jumped over the lazy dog
and ate the programmer

['the quick brown fox', 'jumped over the lazy dog', 'and ate the programmer']

X:\>

```
> -2 votes

# Answer
## Python

```
from sys import stdout as o
i=raw_input("Give me string plz? ")
for x in i+"\n": o.write(x) if x!="\n" else o.write("\n")

```
> -3 votes

---
Tags: code-trolling
---


title: Fibonacci is so QUINE!

text:
# Question
Title: Fibonacci is so QUINE!
1. Your program must output atleast half of its sourcecode in reverse. Any single part of the sourcecode as long as it is one single block of neighbouring characters.
2. Your program should not take any input (from user, filename, network or anything).
3. The output has some additional constraints. The character position (first character is #1) on the output is either a fibonacci-sequence number (1, 1, 2, 3, 5, 8, 13, 21, ...) or not (4, 6, 7, 9, 10, 11, 12, ...), and this is the constraints:

* 3.1 Every third fibonacci-sequence number output position must be a letter (a-z|A-Z). Starting at fibonacci-sequence number #2 (output char|byte pos: 1, 5, 21, ...).
    * 3.2 Every third fibonacci-sequence number output position must be a number (0-9). Starting at fibonacci-sequence number #3 (output char|byte pos: 2, 8, 34, ...).
    * 3.3 Every third fibonacci-sequence number output position must be a symbol !(0-9|a-z|A-Z). Starting at fibonacci-sequence number #4 (output char|byte pos: 3, 13, 55, ...).
4. The output must contain exactly all of these three phrases in any place as long as the other rules is not broken (case sensitive): `Fibonacci is so QUINE!`, `3 is more than {4}`, `{'{"\}`

This is code-golf, shortest sourcecode in bytes wins! Good luck, have fun!

# Answer
# Befunge '98, 91 characters

Was formerly 104, then 101. Saved another 10 chars by moving the "Fi...E!" sentence to output position 89 using `'E'` (instead of `' '` at 55), and moving the actual code into the space this opened up, with a slightly improved print loop.

```
"!ENIUQ os si iccanobiF"f6*>:;#-1,g0;#:_ "}\"f:4++"{'{",,0$,,,,@"}4{ naht erom si 30" b >0a

```

produces the following output (fibonacci positions marked):

```
a0> b "03 is more than {4}"@,,,,$0,,"{'{"++4:f"\}" _:#;0g,1-#;:>*6f"Fibonacci is so QUINE!{'{"\}
--- -  -    -       -            -                    -                                 -
|   |               |                                                                   |
 |     |                         |
  |         |                                         |

```

This snippet outputs all of itself, except for the first character, in reverse order. Then it appends `{'{"\}` to the output, yielding a total of 96 chars including 98.9% of the code.

* Positions 1, 5, 21 and 89 are each occupied by `'a'`, `'b'` or `'E'`.
* Positions 2, 8 and 34 each have a `'0'`.
* In positions 3, 13 and 55, we find `'>'`, `' '` and `';'`, all symbols according to the definition given by Plarsen.

There are 3 completely unused cells, and all of `b >0a` is utterly useless code, only there for the aesthetics of `a0> b 0`. There may (still) be room for optimization.

Since String mode means pushing a reverse string to the stack and then pop/print-ing it forward, writing them in reverse order is totally natural in Befunge.

## Breakdown

1. `f6*` calculates 90, the index of the last character in the source. It's 15 * 6.
2. `>:` means 'head east and duplicate the top of stack value'. Stack \[ ... 90 90 \].
3. `;...;` skips over the code in between.
4. `#:_` skips the `:`, then pops TOS and heads back west if not 0. Stack \[ ... 'F' 90\].
5. Now RTL: `,g0;#:` duplicates TOS, skips entry to the `;` portal, gets the character at (TOS, 0) and prints it.
6. Still RTL: `:;#-1` decrements TOS, skips `;` and duplicates TOS. Execution continues at step 2.) Stack \[ ... 89 89 \]
7. Once the TOS counter is down to 0, `_` lets us through.
8. We push the third required string , whereby we have to calculate the `'"'` because there is no escaping in Befunge. `f:4++` is 15 + 15 + 4. The commas write it back out from the stack. I had to insert `0$` there (push 0 then pop/discard) to meet the requirement.
9. `@` terminates.
> 9 votes

---
Tags: code-golf, quine, fibonacci
---