# Question
Title: Deletion of a blank line in source code which causes unexpected functionality
Write a script that works fine when a blank line is present in the flow of program logic, but breaks or causes unexpected behaviour when that line is removed.

Avoid standard loopholes and stupid answers. Your program should do something "useful," even if all it does is add a few integers.

Removing an empty line from a multiline string doesn't count, unless the expected output from that multiline string shouldn't technically change (ie: if you're removing all blank lines matching `^$`).

Whitespace foolery isn't allowed either; don't do weird things with carriage returns, tabs, spaces, etc.

# Answer
> 62 votes
# Javascript

Opens an alert popup with "Hello, World!" if the blank line exists, otherwise alerts "0".

```
(function(){
    alert(~(arguments.callee+[]).indexOf('\n\n') && "Hello, World!");

})();

```

**Demo**

**Explanation:**

`arguments.callee` is a reference to the self-executing anonymous function.

Appending a blank array (`[]`) casts the function to a string, which gives you its source code.

`indexOf` returns `-1` if the string is not found.

Performing a bitwise not operation (`~`) results in `-1` being turned into `0`, which is a falsey value.

# Answer
> 41 votes
# C

This magic 8-ball program will still work without the blank line, but it will be a bit more decisive — none of the neutral answers will ever appear in the output.

```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
  int x, t;
  char *quotes[] = {
        // Positive :-)
        "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it",
        "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes",
        // Indifferent :-\

        "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again",
        // Negative :-(
        "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" };
  srandom(time(NULL)); // Initialize random number generator
  x = random() % (sizeof(quotes) / sizeof(char*)); // Choose a random outcome
  printf("The Magic Eight Ball says...\n%s\n",quotes[x]);
  return 0;
}

```

### Explanation

> When the C parser sees a backslash followed by a newline character, it ignores both and treats the second line as a continuation of the first. Without the empty line, the "indifferent" answers will all be treated as part of the previous comment.

# Answer
> 36 votes
# Befunge-93

```
v
&
&
+
#

.
@

```

My first befunge program :)

It reads two numbers from the input and prints their sum. If you delete the empty line, it doesn't print anything.

**Explanation:**

`v` sets a downward direction for executing the code
`&` reads an integer
`+` adds the numbers together
`#` skips the next command
`.` prints an integer from the stack
`@` ends the program

As written, `#` skips over the empty line and contines with `.`. Buy when you delete the empty line, `.` is skipped.

There seems to be a nice interpreter at http://befunge.aurlien.net/

# Answer
> 32 votes
# Ruby/Shell

```

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!   The Amazing Integer Adder             !
#! Adds 1 and 1, and displays the result   !
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

p 1+1

```

Works fine if a newline is at the top, otherwise the first comment line is interpreted by the shell as a malformed shebang.

# Answer
> 29 votes
# Scala

```
case class IntWrapper(i: Int)

{
  val answer = (IntWrapper(0) /: (1 to 100)){(x, y) => IntWrapper(x.i + y)} // Add up ints
  println(s"Sum of wrapped integers is $answer")
}

```

If you remove the blank line, no output will be printed. Which is for the best, as your stack would overflow if you actually called `IntWrapper`.

> This is a corner case of Scala's semicolon inference. Normally newlines get a semicolon whenever the resulting code would be valid. However, the Scala devs didn't want to force people to use Egyptian brackets, so it's valid to put the brackets for a class definition on the line immediately after - no semicolon is added, even though one could be. However, a blank line divorces the brackets from the class definition. With the blank line removed, the code changes from being a class definition and a block, to a class definition with a constructor - and a recursive constructor at that!

# Answer
> 27 votes
# GolfScript

```
~{.@\%:

}do;

```

Calculates the GCD of two non-zero integers. Removing the blank line breaks the program.

Try it online.

### How it works

This is a GolfScript implementation of the Euclidean algorithm:

```
      # STACK: "15 24"
~     # Interpret the input string.
{     # STACK: 15 24
  .@  # Duplicate the topmost integer and rotate the other on top of both copies.
      # STACK: 24 24 15
  \   # Swap the topmost integers.
      # STACK: 24 15 24
  %   # Calculate the modulus.
      # STACK: 24 15
}do   # If the modulus is non-zero, repeat the loop.
;     # Discard the last modulus.

```

There's just one tiny problem:

> `{}do` pops the modulus from the stack to check if it's truthy, so it has to get duplicated at the end of the loop. This is normally accomplished by `.`, but `:\n\n` has the same effect: It stores the topmost stack item in the variable LF (`:\n`), then pushes the contents of that variable.

# Answer
> 23 votes
## MediaWiki Template Syntax

Define Template:Foo as

```
{{{a

b|Uh-oh!}}}

```

In another page,

```
{{Foo|a

b=Works!}}  <!-- outputs "Works!" -->

{{Foo|a

b=Works!}}  <!-- outputs "Uh-oh!" -->

{{Foo|a
b=Works!}}  <!-- outputs "Uh-oh!" -->

```

> In MediaWiki, parameter names can contain newlines.

# Answer
> 16 votes
# LaTeX (backref)

The following LaTeX code uses a citation and the citation contains a list of pages, where the entry is citated. Here it is the first page. Package `hyperref` also adds PDF links, the page back reference is red, the citation link is green.

```
\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.

\end{thebibliography}
\end{document}

```

>

But LaTeX does not require the empty line, the empty line looks superfluous and the example will still work without `hyperref` and the empty line:

```
\documentclass{article}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}

```

>

But the links and back reference are gone, thus we reinsert them:

```
\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}

```

But now the example is **broken** and will **not compile** anymore:

```
Runaway argument?
 Donald E. Knuth: \textit {The \TeX book}; Addison Wesley, 1984. \end \ETC.
! File ended while scanning use of \BR@@bibitem.
<inserted text>
                \par
<*> knuth

?

```

What happened? Package `hyperref` (or more precise package `backref`, which is loaded by `hyperref`) wants to get at the end of the bibliography entry to add the back reference list. But the syntax in LaTeX only provides the beginning of the entry by `\bibitem`, the end can be anywhere. In this emergency package `backref` has added a restriction that `\bibitem` has to end the entry with an empty line. Then the package can redefine `\bibitem` to put the back references at the end of the entry.

Since the empty line is missing, TeX keeps looking for it, but found the end of file instead and issues the error message.

# Answer
> 12 votes
# C (semi-obfuscated)

This little program takes a number on the command line and computes its factorial. However, it also contains cutting-edge AI functionality for runtime verification that the company's coding standards, including the correct use of whitespace and blank lines, are being followed. Removing a blank line will trigger the algorithm to reject the insufficiently maintainable program.

No line continuations or trigraphs anywhere. I believe it is valid ANSI C99.

Due to the advanced mathematics involved, if you compile with `gcc`, remember to use `-lm`.

```
#include <setjmp.h>
#include <stdio.h>
#define max(x,y) ((x<y?y:x))
#define swap(x,y) ((x^=y,y^=x,x^=y))
#include <stdlib.h>
#include <math.h>
#define vfry(x,p,z,y,i) (!!y&((z##z##L##I##p##x##z##z)))
#define NDEBUG

/*
 * Proper use of whitespace is essential!
 * Please do not remove any blank lines.
 */

const double E = 2.71828182845904523536;

int vrfy(double epsilon, int magic, const char *key, long int L) {
  /* You are not expected to understand this */
  double x=284.2891,u=2.34e56;
  while (rand()+magic*pow(epsilon,sin(x-E))!=log(u*L))
    x*=vrfy(1.0/epsilon,(int)u,&key[swap(L,magic)],L++);
  return u/lgamma(x);
}

int main(int argc, char *argv[]) {
  int N_=831293812; /* do not change, see Knuth 1987 */
  if (!vfry(E, N,_, "M=&;VT=I!9", 0xfe86ddcaL)) {
    fprintf(stderr, "Code standards violation detected!\n");
    abort();
  }
  if (argc < 2) {
    fprintf(stderr, "Usage: %s n\nComputes n!\n", argv[0]);
    exit(1);
  }
  int m=1, n=atoi(argv[1]), i;
  for (i=1; i <= n; i++)
    m *= i;
  printf("%d! = %d\n", n, m);
  return 0;
}

```

# Spoiler

> The complicated `vrfy` function is never called, but rather the funny-looking `vfry` macro. The use of the preprocessor's string concatenation feature disguises the fact that we are really just checking the parity of `__LINE__`.

# Answer
> 11 votes
# C

This program works as expected (as described in the comments) unless the blank line before `foo = 5;` is removed.

Sadly, I encountered an error almost exactly like this in production code once.

```
#include <stdio.h>

int main()
{
    int foo = 0;

    #define FROB(x) do {                                            \
        x++;                                                        \
        printf("%d\n", x);                                          \
    } while (0);                                                    \

    foo = 5;
    FROB(foo); /* prints 6 */
    FROB(foo); /* prints 7 */
    FROB(foo); /* prints 8 */

    return 0;
}

```

This example uses the `do { ... } while (0)` idiom for creating a multiline statement in a macro (see https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for). It also uses the backslash character to spread a `#define` over multiple lines, conveniently lined up well out of sight. However, it also does two things kind of wrong:

* There is a semicolon after `while (0)`, while the idiom usually omits this
* There is a backslash after the final line of the `#define`

With this in place, removing the blank line before `foo = 5;` causes that assignment to be executed *after* the `printf`, but also after *every* invocation of the `FROB` macro. As a result, the output after removing the blank line is:

```
1
6
6

```

# Answer
> 9 votes
# C/C++

```
int main(){

    return __LINE__ - 3;
}

```

Returns success and can be used as an implementation for true. If the empty line is removed you can use it as an implementation for false instead.

# Answer
> 8 votes
## PowerShell

This function will add two numbers.

```
function add ($a, $b) {
    $numbers = @($a `

            $b)
        $numbers| measure -sum| select -expand sum
}

```

Removing the blank line will cause the function to fail with: `Unexpected token '$b' in expression or statement.`

**Explanation**

> Array elements can be separated by newlines and/or commas. Placing the line continuation character (```) after `$a` requires an extra newline to separate `$a` and `$b`. Otherwise, the interpreter views the code as `$numbers = @($a $b)` (no element separator).

# Answer
> 7 votes
## TeX

```
\noindent\everypar{$\bullet$ hello }

world
\bye

```

Without the empty line, "hello" is not printed.

**Explanation**

TeX treats the empty line as a paragraph break, and `\everypar` is executed at the start of a new paragraph.

# Answer
> 6 votes
# Java

```
import java.util.Scanner;

public class BlankLine
{
    public static void main( String[] args )
    {
        //This calculates 2^ given number
        //if you remove blank line after the next line it will always print 1
        int x = new Throwable().getStackTrace()[0].getLineNumber();

        int y = new Throwable().getStackTrace()[0].getLineNumber() - x;
        System.out.println("Number:");
        Scanner scanner = new Scanner(System.in);
        int r = 1;
        int n = scanner.nextInt();

        for(int i = 0; i < n; i++){
            r *= y;
        }
        System.out.println("2^number: "+r);
    }
}

```

> x is current line number, y is current line number - x. If there is blank line between them the result is 2. So the code calculates 2 ^ number.

# Answer
> 6 votes
# Perl 5

```
print(<<""
Hello, World!

);

```

This code prints `Hello, World!`. Removing the blank line gives a syntax error instead.

Explanation:

> Perl's here-doc syntax for multi-line strings allows an empty terminator string. It's even explicitly documented. Removing the blank line causes the closing parenthesis (and everything else up to the next blank line, if there is one) to be interpreted as part of the string, causing a syntax error.
>
> The error messages you get are actually pretty decent, for such an oddball syntax feature. If there are no blank lines at all in the program after the `print(<<""` line, Perl simply says:
>
> ```
> Can't find string terminator "" anywhere before EOF at foo.pl line 1.
> ```
>
> If there *is* an empty line at the end of the program, you get something like this instead:
>
> ```
> syntax error at foo.pl line 4, at EOF
>   (Might be a runaway multi-line << string starting on line 1)
> Execution of foo.pl aborted due to compilation errors.
> ```

# Answer
> 5 votes
## Batch

```
@echo off
setLocal enableDelayedExpansion
set NL=^

echo Hello!NL!World

```

This code will output `Hello` and on the next line `World`. When either or both of the blank lines are removed, it outputs nothing at all.

There is an explanation here.

# Answer
> 4 votes
# Ruby

Deletion of the first line will cause error:

```

line = IO.readlines($0).first.chomp
if line.empty?
puts 34+4
else
raise "Please add a newline at the beginning of the program."
end

```

# Answer
> 4 votes
# Python

Don't know if this falls under the standard loopholes, I looked at the list and didn't see this.

```
src = open(__file__, 'r')
code = src.readlines()
src.close()

if code[3] == '\n':
    print 'Hello World!'

```

Running this regularly returns

```
Hello World!

```

Running it without the blank line on line 4, ie like below:

```
src = open(
__file__, 'r')
code = src.readlines()
src.close()
if code[3] == '\n':
    print 'Hello World!'

```

returns nothing.

# Answer
> 3 votes
# Python 2.x

This program outputs the fifth character of the inputted string.

```
import inspect

text = raw_input()
print 'Fifth character of the string:', text[inspect.getlineno(inspect.currentframe())]

```

This isn't in any way hidden. If you remove the empty line, it gives the fourth character and the sixth if you add one.

# Answer
> 3 votes
## Tcl

A function that adds two numbers (and checks if the newline have been deleted):

```
proc add {a b} {
    if {[llength [split [info body add] \n]] < 5} {error "function has been modified"}

    return [expr $a+$b]
}

```

There's nothing to hide here, it does what it says, so I'm not spoilerizing the explanation. The function `info` is a swiss army knife of introspection (what other languages call reflection). `info body` returns the source code of a function (if not written in C or assembly).

I have to admit that this had me stumped until I saw the javascript solution.

# Answer
> 3 votes
# C

```
#include <stdio.h>

int main() {
    const char* a = "You love blank lines.";
    #define print_out(a) \

    printf("%s\n", a);
    a = "You don't seem to love blank lines";
    print_out(a);
    return 0;
}

```

With the blank line, `a` is the local variable a and without it's the macro parameter...

# Answer
> 3 votes
Technically not a "code" issue, but a server one. If this is sent to Apache from a CGI script (which can be generated with any language you please), it will send an HTTP response to the client:

```
HTTP/1.x 200 OK
Content-Type: text/html; charset=UTF-8

Hello world!

```

On the other hand, this will fail as it is missing the blank space after the header.

```
HTTP/1.x 200 OK
Content-Type: text/html; charset=UTF-8
Hello world!

```

# Answer
> 2 votes
**JavaScript**

The function `whereami` responds with the position of the calling line, relative to its own position in the source code.

```
console.log (whereami ()) //3 line(s)  before me

function whereami () {
    var a=function a(e){try{to}catch(c){for(var d=c.stack.split("\n"),b=0;b<d.length&&!~d[b].indexOf("a");b++);return c.stack.split("\n")[b+~~e].match(/:(\d+)/)[1]-~~window.hasOwnProperty("__commandLineAPI")}},a1=a(1),i

    i= a(2)>a(1)+4?a(1):a(1)>a1+2?a1-1:a/a1

    return ((i=(a(2)<i?i-1:a(1)>i+3?a(2)-a(1)-1:a/1)) + " line(s) "   ) + (i<a(2)?" after":(i>=a(2)?" before":"confusing")) + " me";
}

console.log (whereami ()) //3 line(s)  after me

```

If any blank line in the `whereami` function is removed. The output is `NaN line(s) confusing me`. *(Adding lines doesn't break it)*

> It actually only counts how many lines are between `i` and the first and last line respectively. If they fall under a given value. The reference line is set to `NaN` which neither satisfies `NaN<callingLine` nor `NaN>=callingLine`. I tried to hide it a bit in unreadable ternary expressions.

# Answer
> 2 votes
# Perl

```
#!/usr/bin/perl

use strict;
use warnings;

open IN, "<".$0 or die "Did not find input files!";
while (<IN>) {
        m/blabla/ && ((<IN> =~ /\}/ && print "tra-la-la...\n") || print "ti-ri-li\n");

}
close IN;

```

> This perl script will read the script file and check if after the line containing "blabla" there is a closing bracket.

# Answer
> 2 votes
## Escript

Due to bug in `escript` implementation valid escript has to be at least three lines long and first line hast to be shebang line or empty line. So following script hast to have two empty lines where first one has to be first one:

```
main(_) -> io:format("Hello world!~n", []), halt().

```

Or it hast to be broken in two lines but still has to have first empty line.

```
main(_) ->
    io:format("Hello world!~n", []), halt().

```

Otherwise you will get

```
escript: Premature end of file reached

```

# Answer
> 2 votes
# Ruby

```
print %q
2+2=

p(2+2)

```

Prints `2+2=4`, but gives a syntax error without the blank third line. `%q` allows any non-word character to serve as a string delimiter, even the newline character. So the first three lines of code are actually equivalent to `print %q"2+2="`, or just `print "2+2="`. Since the newline after `2+2=` is being used as a quote delimiter, it's not also parsed as a *line* delimiter, so you need another one immediately after.

# Answer
> 1 votes
# Insomnia (both versions)!

```
Þyoo

â

```

This code prints a ~ (don't ask why, insomnia is weird). If you remove the blank line, it prints a ÿ instead.

By the way that first letter is a thorn.

# Answer
> 0 votes
## C++

This is a classic and rather dumb trick. You will know what it is when you see it, this is just here for completion's sake. As such, I'm marking this as a community wiki answer.

```
int main() {
    //This program won't work without the next line, why??/

    return 1;
}

```

Why this works

# Answer
> 0 votes
Paste this into a html file, and open it in your browser. It's pretty simple, but a little tricky because it takes the number of blank lines in the document and indexes an array to call a function which shows an alert.

```
<body>
<script>
[null, function(){alert("GIVE ME MY LINE BACK")}, function(){alert("2 + 2 = " + (2+2))}][document.body.innerHTML.split("\n\n").length]()

</script>
</body>

```

This one is borderline rule breaking. Technically JavaScript doesn't have multiline strings, which is the only reason this works.

Because you can have a syntax error in one script tag without interfering with the other script tags this shows a positive result only if there's an error on the page. The error prevents the second alert from firing because it's in the same script tag.

```
<body>
<script>
window.onerror=function(){
  alert("2 + 2 = " + (2+2));
}
</script>
<script>
var a = "\

";
alert("GIVE ME MY LINE BACK!");
</script>
</body>

```

# Answer
> 0 votes
Ruby

```
puts (% #{ARGV[0].to_i + ARGV[1].to_i}

)

```

The secret is that the newline, is really a tab, then a new line. I don't know if this counts but I thought it was cleaver. The character after the `%` is also a tab, but for some reason it doesn't show up like one. I'm using Ruby's percent notation to make a string, that adds the first 2 arguments passed to the script. There's more on that here: http://teohm.com/blog/2012/10/15/start-using-ruby-percent-notation/

# Answer
> 0 votes
# AppleScript

```
say¬

quit
```

This code is absolutely meant to throw an error, as it matches (in compiler speak) to this:

```
¬
   say
quit
```

Which throws the error `"Can’t make current application into type text."`

However, if you delete the second line, you get the equivalent of this code:

```
say ¬
   (quit)
```

Which says nothing and attempts to close the current application (Script Editor or Terminal).

# Answer
> 0 votes
## \>\<\>

This program

```
02.

v"?"o
;"!"o

```

outputs

```
?

```

and exits.

Removing the blank line cause it to output

```
!

```

---
Tags: popularity-contest, underhanded
---


title: Restaurant Shorthand

text:
# Question
Title: Restaurant Shorthand
# Goal

Sometimes dinner menus can have long winded names. It's much easier for the waiter to write an abbreviation that unambiguously identifies the dish.

For example, given this list:

```
beef burger
chicken burger
chicken nuggets

```

The abbreviation `c n` matches `chicken nuggets`.
The abbreviation `bur` matches `beef burger` and `chicken burger`.

Write a program of function that identifies one or more items that match an abbreviation.

# Input

1. The abbreviated string to find.
2. A list of items to search.

You may change this order and use any suitable data types.

# Output

* If the abbreviation does not match any items: `Not found`
* If the abbreviation unambiguously matches an item: output the unabbreviated item.
* If the abbreviation ambiguously matches several items: output a comma separated list of words that would make the selection unambiguous, followed by a question mark. The order is not important. Extra spaces are permitted.

# Matching rules

Each word in the abbreviation and the items is considered separately. If an abbreviated word matches the start of an item word, the item is a potential match. If none of an item's words start with any if the abbreviated words, that item is not a match.

Abbreviated words can be in any order.

An abbreviated word cannot be used to match multiple item words and visa-versa.

Abbreviations only match the start of words.

Assume no item will contain all of the words of another item. For example, you will never have `beef burger` and `beef cheese burger`.

# Test Cases

Given this list:

```
beef burger
crispy chicken burger
grilled chicken burger
chicken nuggets
chocolate cone
strawberry cone
vanilla cone

```

These abbreviation give the specified output:

```
fish           Not found
cones          Not found
chicken cone   Not found
nilla          Not found
v              vanilla cone
be             beef burger
c n            chicken nuggets
b b            beef burger
c b c          crispy chicken burger
c b            crispy,grilled?
bu             beef,crispy,grilled?
            or beef,crispy chicken,grilled chicken?
ch             crispy,grilled,nuggets,cone?
            or crispy chicken,grilled chicken,nuggets,cone?

```

# Scoring

This is code golf. The shortest answer in bytes in 12 days wins acceptance. (I would have made it one week, but I won't be around for that.)

# Answer
> 1 votes
# Python 2 - 181 bytes

It turns the abbreviated string into a regex and attempts to match groups from the search list.

The ternary operation `if` and `else`s are 14 bytes. I've tried to cut it down into a list and then accessing one of the items based on the state of `r`, but don't have anything shorter that this yet.

```
import re
def s(a,l):
 r=[m.group(1)for e in l for m in[re.compile('^('+a.replace(' ','\w+ ')+'\w+)$').search(e)]if m]
 print','.join(r)+'?'if len(r)>1 else r[0]if r else'Not found'

```

Call with `s(str, list)`:

```
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar', 'cfoo nbar'])
>>> chicken nuggets,cfoo nbar?

```

---
Tags: code-golf, search
---


title: RTTTL Obfuscation

text:
# Question
Title: RTTTL Obfuscation
**RTTTL**, or *Ring Tone Text Transfer Language* is a music format that was invented by Nokia ~~in the dawn of time when dinosaurs roamed the land~~. It allows for fairly crude pieces of music (no chords or anything), and the format is pretty simple which is why I think it's pretty cool. Take a look at this one:

```
DejaVu: d=8,o=5,b=200: e, e, c, e, g, 2g4

```

Let's dissect the format. The "DejaVu" part at the beginning is the title -- this cannot be longer than ten characters. The d and o are the default values for duration and octave -- if a note doesn't specify duration or octave, it'll use these. Finally, the b is the beats per minute.

After that, the actual notes of the song are listed. The format of a note is DPO, where D is the duration of the note (1, 2, 4, 8, 16), P is the pitch (A,B,C,D,E,F,G,A#,B#,C#,D#,E#,F#,G#), and O is the octave (4-8 in the Nokia implementation, however it is different for other implementations. For the purposes of the challenge we'll say it is 1-8). If the duration or the octave is not specified, the defaults are used. Additionally, a note can have a dot after it -- this essentially multiplies the duration by 1.5.

In our example here, we have two E notes with no duration and octave, which mean that they have the default duration and octave (8, or eighth-note and octave 5), a C with no duration and octave, an E and a G. The final note is a G note with a duration of 2 (half-note) and an octave of 4.

Now that we've gone over the format, what's the challenge? The challenge actually doesn't have too much to do with RTTTL. Your task is to create an obfuscated program that outputs "Hello, World!" (exactly) that is also **a valid RTTTL song that is at least five seconds long**.

In order to test your RTTTL song, you can use this site to convert your song to a MIDI file, then listen to it in a MIDI player. This is . Good luck!

EDIT: Here's a website for converting MIDIs to RTTTLs if you so desire. Link

EDIT2: This shiny bounty will be awarded to the winner (most upvoted post) in 7 days.

# Answer
> 13 votes
# Whitespace, 2748 Bytes

(replace `\t` with actual tabs)

```
Hello:d=4, o=5, b=120:2p, 16a2,
16p, 16a2, 16p, 16a3,\t16p, 16a3, 16p,\t16g2, 16p, 16g2, 16p,
16g3,\t16p,\t16g3, 16p, 16a2, 16p, e3,\td3,
16b2, 16c3, 16b2, 16a2,\t8g2,\t16a2, 16p, 16a2,\t16p, 16a3,\t16p,
16a3,\t16p,\t16g2, 16p, 16g2, 16p, 16g3,\t16p, 16g3,
16p, 16a2, 16p, e3,\td3,\t16b2, 16c3,\t16b2,\t16a2, 8g2, 16a2,
16p,\t16a2,\t16p, 16a3, 16p, 16a3, 16p,\t16g2,\t16p,
16g2, 16p, 16g3, 16p,\t16g3,\t16p, 16a2,\t16p,\te3, d3, 16b2,
16c3,\t16b2,\t16a2, 8g2, 16a2, 16p, 16a2,\t16p, 16a3, 16p,
16a3, 16p, 16g2, 16p,\t16g2,\t16p, 16g3,\t16p,\t16g3,\t16p,\t16a2,
16p,\te3,\td3, 16b2, 16c3, 16b2, 16a2,\t8g2, 16a2,\t16p,
16a2, 16p, 16a3, 16p,\t16a3, 16p,\t16g2,\t16p, 16g2, 16p,
16g3,\t16p,\t16g3, 16p, 16a2, 16p, e3,\td3,\t16b2, 16c3,
16b2, 16a2, 8g2, 16a2,\t16p, 16a2, 16p, 16a3, 16p, 16a3,
16p,\t16g2,\t16p, 16g2, 16p, 16g3, 16p,\t16g3,\t16p,\t16a2,
16p, e3, d3, 16b2,\t16c3,\t16b2,\t16a2, 8g2,\ta2,\t8c#3,\t8e3,
g2,\t8b2,\t8d3, a2, 8c#3, 8e3, g2,\t8b2, 8d3, a2, 8c#3,
8e3, g2, 8b2, 8d3,\ta2,\t8c#3, 8e3,\tg2,\t8b2,\t8d3,\ta2,
8c#3,\t8e3,\tg2, 8b2, 8d3, a2, 8c#3,\t8e3, g2, 8b2,\t8d3,
a2, 8c#3, 8e3, g2,\t8b2,\t8d3,\ta2, 8c#3, 8e3,\tg2, 8b2,
8d3,\t16a2,\t16p, 16a2, 16p, 16a3, 16p,\t16a3, 16p,\t16g2, 16p,
16g2, 16p, 16g3, 16p,\t16g3,\t16p, 16a2,\t16p,\te3, d3, 16b2,
16c3,\t16b2,\t16a2, 8g2, 16a2, 16p, 16a2,\t16p, 16a3,\t16p,\t16a3,
16p, 16g2, 16p, 16g2,\t16p,\t16g3, 16p, 16g3,\t16p, 16a2, 16p,
e3,\td3,\t16b2, 16c3, 16b2, 16a2, 8g2,\t16a2,\t16p, 16a2, 16p,
16a3, 16p, 16a3, 16p,\t16g2, 16p, 16g2, 16p, 16g3,\t16p,
16g3,\t16p,\t16a2, 16p, e3, d3, 16b2,\t16c3,\t16b2, 16a2,\t8g2,
16a2, 16p, 16a2, 16p,\t16a3,\t16p, 16a3,\t16p,
16g2,\t16p,\t16g2, 16p, 16g3, 16p, 16g3,\t16p,\t16a2,\t16p, e3,
d3, 16b2, 16c3, 16b2,\t16a2, 8g2,\ta2, 8c#3,
8e3,\tg2,\t8b2, 8d3, a2, 8c#3, 8e3,\tg2,\t8b2,\t8d3,\ta2,
8c#3, 8e3, g2, 8b2, 8d3,
a2,\t8c#3,\t8e3, g2, 8b2, 8d3, a2, 8c#3,
8e3,
g2, 8b2, 8d3, a2, 8c#3,\t8e3,
g2, 8b2,
8d3, a2,\t8c#3,\t8e3,\tg2, 8b2,
8d3, a2,
8c#3,\t8e3, g2, 8b2,\t8d3, 1a3,
1a2,\td3,
8f#3, 8a3, c3, 8e3, 8g3, d3,\t8f#3,
8a3,\tc3, 8e3, 8g3, d3,
8f#3, 8a3,
c3, 8e3, 8g3,\td3,
8f#3,
8a3, c3, 8e3, 8g3,\td3, 8f#3,
8a3,
c3,
8e3,
8g3,d3,8f#3,8a3,c3,8e3,8g3,d3,8f#3,8a3,c3,8e3,8g3,d3,8f#3,8a3,c3,8e3,8g3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,

```

It's a horrible ringtone version of The Doors with *Hello, I love you*.

Download converted MIDI

# Answer
> 8 votes
# H9+, 157,007 bytes

MIDI!!!!

Is too long for the post. So here, have a pastebin. (The pastebin doesn't have proper capitalization, FYI.) I used the following softwares:

The song is "Anthem of our Dying Day", by Story of the Year. It is the full, 3.5 minute song. `^-^`.

It starts out with:

```
ANTHEM:d=4,o=5,b=120:172c#,86f#,86a4,172p,16p,43a4,86p,43f#4,172a4,10p,57a4,...

```

`H`, of course, prints `Hello, World!`. And there are no `9`s nor `+`s in the code, I made sure. Good thing this isn't a .

# Answer
> 7 votes
# 123, 816 Bytes

```
H:d=4,o=4,b=400:2a,2b,2a,2b,1a,1b,2a,1b,1a,2b,1a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,1a,2b,1a,1b,1a,2b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,2b,2a,1b,1a,2b,1a,1b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,1a,3b,1a,2b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,2b,1a,1b,2a,1b,3a,3b,1a,2b,1a,1b,2a,1b,3a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,2b,1a,1b,3a,3b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,1b,1a,1b,2a,1b,1a,2b,3a,3b,1a,1b,2a,3b,3a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,1b,2a,1b,1a,1b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,1a,1b,1a,1b,2a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,1a,1b,2a,1b,1a,2b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,1b,1a,2b,1a,1b,2a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,1b,3a,3b,1a,2b,1a,1b,2a,1b,3a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,3a,3b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,1a

```

Download tune

This one is just rhythmic beeping, but the language surely has more potential for this challenge, since in 123, all characters except 1, 2 and 3 are ignored. Credits for the original 123 code go to Martin Büttner.

# Answer
> 2 votes
# Python 2.7, 1606 bytes

Okay, so it's not amazingly obfuscated, but it does work. I've converted it to a midi file and it does play.

The tune is *Still Alive* from Portal. I got the tune as a midi file from here, which I then converted into a RTTL. The last few notes are off, but I think that's okay.

```
print[':d=4,o=5,b=120:2p,8g,8f#,8e,8e,2f#,1p,8a4,8g,8f#,8e,e,f#.,d,8e,1a4,8p,8a4,e,8f#,g.,8e,c#,d.,e,8a4,a4,1f#,2p,8g,8f#,8e,8e,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d.,8e,2a4,2p,e,8f#,g.,8e,c#.,8d,e,8a4,8d,8e,8f,8e,8d,8c,p,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,a,g,8f,8g,8a,8a,g,f,8d,8c,8d,8f,8f,e,8e,8f#,8f#,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,p.,8a4,8g,8f#,8e,8e.,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d,e,2a4,2p,e,8f#,g.,e,c#,8d,e.,8a4,a4,2f#,2p,8a4,8p,8b,8p,8a,8p,8g,8p,8g,8p,a,1p,8a4,8p,8b,8p,8a,8p,8g,8p,g.,p.,8a,8p,f#.,p.,8g,8p,2d,2p,e,8f#,g.,e,c#,8d,e,8a4,8d,8e,8f,8e,8d,c.,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,8a,8a,g,8f,8g,8a,8a,8g,8f,f,8d,8c,8d,8f,8f,e,8e,8f#,2f#,1p,8a4,8g,8f#,8e,8e.,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d,e,2a4,2p,e,8f#,g.,e,c#,8d,e.,8a4,a4,2f#,2p,8a4,8p,8b,8p,8a,8p,8g,8p,8g,8p,a,1p,8a4,8p,8b,8p,8a,8p,8g,8p,g.,p.,8a,8p,f#.,p.,8g,8p,2d,2p,e,8f#,g.,e,c#,8d,e,8a4,8d,8e,8f,8e,8d,c.,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,8a,8a,g,8f,8g,8a,8a,8g,8f,f,8d,8c,8d,8f,8f,e,8e,8f#,8f#,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,a.,p.,8g,8a,a.,p.,8g,8f#,2f#',''.join(map(chr,[72,101,108,108,111,44,32,87,111,114,108,100,33]))][1]

```

# Answer
> 1 votes
# Lenguage

```
Hello: d=8,o=4,b=130: a, b, 4e5, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, 4e5, a, b, 4e5, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, e5, e, 4e, a, 4a., b, 4b., c5, 4c.5, 4d.5, 4c5, 2d5, p, g, b, 4e5, f, a, e5, e, e, 4a, 4a, 4b, 4b, 4c5, 2c5, b, c5, 4b, 2a, p, g, b, 4e5, f, a, e5, e, 4e, a, 4a., b, 4b., c5, 4c.5, 4d.5, 4c5, 2d5, p, g, b, 4e5, f, a, e5, d5, 2e5, a, b, 4e5, g, b, 4e5, g, b, d5, c5, e5, 4d.5, d5, c5, 4e5, a, c#5, 4e5, a, c#5, d5, e5, f5, e5, e5, d5, 2d5, g, b, 4d5, g, b, c5, d5, e5, d5, d5, c5, c5, g, 4a, f, a, 4c5, f, a, a#, c5, 4d.5, 4c.5, c5, a#, 4a, 2g#, f#, g#, 4a, a, 4b, a, 4c5, a, c5, 4e5, a, c5, d5, e5, 4f5, f5, 4f5, e5, 4d5, g, b, 4d5, g, b, c5, d5, 4e5, f5, 4e5, d5, c5, g, 2a, f, a, a#, c5, 4d5, c5, 4c5, 4a#, 4a, 2g#., 2p., p, f#, g#, 2a, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, 4e5, 4a, 4c#5, 1e5

```

Followed by many gazillions of spaces so that the total length is 150306725405247424813082671095009555930972306375297366901721134222563463360025683976401363734706798738542991492

Convert and download (note: the code is truncated to save bandwidth, but the resulting midi should be the same)

---
Tags: popularity-contest, hello-world, music, obfuscation
---


title: How can Pyth be improved?

text:
# Question
Title: How can Pyth be improved?
Pyth is in ongoing development, meaning that new features are being added all the time.

I want to make Pyth a better langauge, so I'd like to know what features people are looking for.

This is the place the post ideas you have for making Pyth better.

In your answer, please state:

* What you'd like to see changed/added.
* An example usage of the change.

I'll comment if I'm planning to implement the suggestion.

Please check if the idea you want to suggest has already been suggested. Upvote ideas you'd like implemented.

---

Implemented suggestions:

---

This was on topic as per this meta question when I posted the question, it is no longer clear.

# Answer
> 7 votes
## Nested loops

If you want to nest `for` loops, you currently have to waste a byte for using `F<var><seq>` inside a `V<seq>` or vice versa. I'd love to have the same thing as with lambdas, where the variable used for the loop would change when nesting loops.

# Answer
> 5 votes
# Turt

Pyth equivalent of turtle graphics, as per `import turtle`.

# Answer
> 4 votes
## Easier Module Importing

So far, every time I have used `$` it has been something like:

```
$from <module> import <function> as <pyth-function-with-same-arity>$
for example:
$from unicodedata import name as neg$

```

There could be a new function that summarized this for example `.$`:

```
.$"unicodedata""name""neg"
.$"unicodedata name neg"

```

Or using the newer syntax like `_M` which may not be easy/possible to do:

```
_$unicodedata name$

```

In addition, one function with each arity could be given a single letter macro name so that these calls could be shorter (except for the `_$` option).

# Answer
> 4 votes
# Sleeping

This caused trouble here, and @mbomb007 suggested to put it as an improvement to Pyth. Basically, right now, in order to sleep for the given number of seconds, I need to do something like:

```
Q$__import__('time').sleep(Q)$

```

Which is annoying and long as heck.

# Answer
> 4 votes
# More lambdas

*This is really FryAmTheEggman's idea, but I'm posting it to get it out there.*

Sometimes I find that using two different one-argument lambdas would shorten the code, while having to use a two-argument lambda for one wouldn't.

It would be nice to have `L`, `M` and friends redefine a different function every time used; for example, this code:

```
L*b2L*b3y5'5

```

could compile to:

```
@memoized
def subsets(b):
 return times(b,2)
@memoized
def read_file(b):
 return times(b,3)
imp_print(subsets(5))
imp_print(read_file(5))

```

The exact choice of functions could be changed, of course.

# Answer
> 3 votes
## Improved multi-dimensional arrays

Using multi-dimensional arrays is rather hard to do currently. For example, the C code `A[B][C][D]` would translate to `@@@ABCD` in Pyth. Something like `@A[BCD)` would be much nicer (albeit not any shorter here). The same also goes for `X`; `A[B][C][D] = E` is currently `X@@ABCDE`, when it could be `XA[BCD)E`.

# Answer
> 3 votes
## Some minor ideas

* Absolute difference, i.e. `abs(val1 - val2)`. Currently it's `.a-<val1><val2>`.
* `min`/`max` for values. Currently it's `hS,<val1><val2>`/`eS,<val1><val2>` or the same thing with more values. (`hS<seq>`/`eS<seq>` for sequences is short enough.)

# Answer
> 3 votes
Not a Pyth feature, but nevertheless...

## Modularize the Pyth code

This only affects Pyth under the hood. Some parts of the Pyth implementation are quite messy. Lots of global variables and other hacky things.

I really got frustrated a few days ago, when I tried using a few functions of the Pyth implementation (like executing a string of Pyth commands) from another Python script.

Something like the following would be nice:

```
from pyth import execute_pyth
print(execute_pyth(code='sQ', input='[1, 2, 3]'))

```

Well, I guess this is just a help call for Pyth5.

# Answer
> 1 votes
# Unique elements

Pyth currently has no short way of getting unique elements of a sequence. You can *test* if it's unique, but you can't get the items that are actually unique. Currently, the shortest way is:

```
{.-Q{Q

```

6 bytes! Compare that to K, where getting the unique elements is a one-byte operation: `=x`.

Maybe `.}` would work here?

---
Tags: tips, pyth
---


# Question
Title: Given a table of wins, losses and draws, output the result of each match in a sports tournament
This question is inspired by ongoing tournament of "the hooligan's game played by gentlemen", the Rugby World Cup, which has just completed the pool stage. There are 20 teams in the tournament, and they are divided into 4 pools of 5 teams each. During the pool stage each team plays against all the other teams in their pool (a total of 10 matches per pool), and the top 2 teams of each pool progress to the knockout stage.

At the end of the pool stage there is a table for each pool showing the number of wins, losses and draws for each team. The challenge for this question is to write a program that inputs the count of wins, losses and draws for each team in a pool, and from that information outputs the individual results of each of the 10 matches (who won, lost or drew against who) if possible or outputs an error message if not.

For example, here is the table for Pool D of this year's tournament:

```
            Win    Loss    Draw
Canada        0       4       0
France        3       1       0
Ireland       4       0       0
Italy         2       2       0
Romania       1       3       0

```

From this information, we can deduce that Ireland won against Canada, France, Italy and Romania, because they won all their games. France must have won against Canada, Italy and Romania but lost to Ireland, because they only lost one and it must have been to the undefeated Ireland. We have just worked out that Italy lost to Ireland and France, so they must have won against Canada and Romania. Canada lost all their games, and so Romania's win must have been against Canada.

```
         Canada  France Ireland   Italy Romania
Canada        -       L       L       L       L
France        W       -       L       W       W
Ireland       W       W       -       W       W
Italy         W       L       L       -       W
Romania       W       L       L       L       -

```

Here's a more complicated (fictional) example:

```
            Win    Loss    Draw
Canada        3       1       0
France        1       2       1
Ireland       0       3       1
Italy         0       2       2
Romania       4       0       0

```

In this case, we can deduce that Romania won against Canada, France, Italy and Ireland, because they won all their games. Canada must have won against Ireland, Italy and France but lost to Romania. We have just worked out that Italy lost to Romania and Canada, so they must have drawn against France and Ireland. That means Ireland drew with Italy and lost to everyone else, and therefore France must have beaten Ireland, drawn with Italy and lost to Canada and Romania.

```
         Canada  France Ireland   Italy Romania
Canada        -       W       W       W       L
France        L       -       W       D       L
Ireland       L       L       -       D       L
Italy         L       D       D       -       L
Romania       W       W       W       W       -

```

Some tables are unsolvable, for example this year's Pool B, in which 3 teams got the same W/L/D totals:

```
            Win    Loss    Draw
Japan         3       1       0
Samoa         1       3       0
Scotland      3       1       0
South Africa  3       1       0
United States 0       4       0

```

However some tables with duplicate rows are solvable, like this (fictional) one:

```
            Win    Loss    Draw
Japan         4       0       0
Samoa         0       3       1
Scotland      2       2       0
South Africa  0       3       1
United States 3       1       0

```

# Input

Your program or function should accept 15 numbers specifying the win, loss and draw totals for each of the 5 teams. You can use any delimiter you want, input the numbers in row or column major order, and accept the numbers either via stdin or passed via an array to a function.

Because wins + losses + draws = 4, you can omit one of the values and work it out from the others if you wish, meaning that you only have to input 10 numbers.

You don't need to input any team names.

*Sample input:*

```
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0

```

# Output

Your program or function's output should be in the form of a 5 x 5 grid printed to stdout, or an array returned from a function. Each element should specify whether the team given in the row position won, lost or drew against the team in the column position. The row ordering for the output should match the input. You can define what denotes a win, loss or draw, so the letters W, L, D or digits 0 1 2 or whatever you want can be used as long as they are clearly defined and can be distinguished from each other. Diagonal elements are undefined, you can output anything, but it should be the same in each case. Values can be separated with commas, spaces or whatever character you like, or not character. Both input and output can be formatted with all values on a single line if desired.

If a table does not have a unique solution then you must output a simple error message of your choice.

*Sample output:*

```
- W W W L
L - W D L
L L - D L
L D D - L
W W W W -

```

*Sample output for unsolvable table:*

```
dunno mate

```

This is code golf so the shortest program in bytes wins.

Pic related (Japan versus South Africa):

# Answer
# CJam, ~~57~~ ~~49~~ ~~47~~ 45 bytes

```
{JZb:af{.*e_1+e!}:m*:e_5f/{_z2\ff-=},_,(0@?~}

```

This is an anonymous function that pops a two-dimensional array from the stack and leaves one in return. It contains `2` for wins, `1` for draws and `0` for losses. It also contains `1` for diagonal elements , for which *you can output anything*. If the problem isn't solvable, the function returns `-1`.

The code will work online, but it will take a while. Try it in the CJam interpreter.

### Test run

```
$ cat input
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0
$ time cjam results.cjam < input
[1 2 2 2 0]
[0 1 2 1 0]
[0 0 1 1 0]
[0 1 1 1 0]
[2 2 2 2 1]

real    0m1.584s
user    0m4.020s
sys     0m0.146s

```

### How it works

```
JZb:a e# Push 19 in base 3; wrap each digit in an array. Pushes [[2] [0] [1]].
f{    e# For each row of the input, push it and [[2] [0] [1]]; then:
  .*  e# Repeat 2, 0 and 1 (win, loss, draw) the specified number of times.
  e_  e# Flatten the resulting array.
  1+  e# Append a 1 for the diagonal.
  e!  e# Push all possible permutations.
}     e#
:m*   e# Cartesian product; push all possible combinations of permutations.
:e_   e# Flatten the results.
5f/   e# Split into rows of length 5.
{     e# Filter:
  _z  e#   Push a transposed copy of the array.
  2\  e#   Swap the result with 2.
  ff- e#   Subtract all elements from 2.
  =   e#   Check for equality.
},    e# Keep the element if `=' pushed 1.
_,(   e# Get the length of the array of solutions and subtract 1.
0@?   e# Keep the array for length 1, push 0 otherwise.
~     e# Either dump the singleton array or turn 0 into -1.

```
> 4 votes

# Answer
# Haskell, ~~180~~ 177 bytes

```
import Data.List
z=zipWith
m=map
a#b|(c,d)<-splitAt a b=c++[0]++d
f t=take 1[x|x<-m(z(#)[0..])$sequence$m(permutations.concat.z(flip replicate)[1,-1,0])t,transpose x==m(m(0-))x]

```

A win is shown as `1`, a loss as `-1` and a draw as `0`. Diagonal elements are also `0`. Unsolvable tables are empty lists, i.e. `[]`.

Usage example: `f [[3,1,0],[1,2,1],[0,3,1],[0,2,2],[4,0,0]]` -\> `[[[0,1,1,1,-1],[-1,0,1,0,-1],[-1,-1,0,0,-1],[-1,0,0,0,-1],[1,1,1,1,0]]]`.

How it works: brute force! Create a list of wins/losses/draws according to the input, e.g. `[3,1,0]` -\> `[1,1,1,-1]`, permute, build all combinations, insert diagonals and keep all tables that are equal to their transposition with all elements negated. Take the first one.
> 4 votes

---
Tags: code-golf
---


# Question
Title: Seamless conversion from square to hexagon
For many games played on a grid, hexagons are the Clearly Superior Choice™. Unfortunately, many free game art sites only have seamless tile sets for square maps. On a past project, I used some of these, and manually converted them to hexagons.

*However*, I've gotten lazy in my old age. It should be easy to automate the process with a small script.

*However*, I've gotten lazy in my old age. So I'm outsourcing it to you, and disguising it as a code golf challenge1.

---

## Input

Input is a square image in any common image format capable of 24-bit RGB color. You may also take a filename as input instead of the image data itself.

You may assume the image is square, and that the side length is a multiple of four.

## Output

Output is the input tile, but converted to a hexagon (the image itself will be square, with transparent areas). You may save it to a file or display to the screen.

Again, any common image format will do. If the format you're using supports transparency, background areas must be transparent. If it doesn't, you may use color #FF00FF (that horrible fuchsia one) as a stand-in.

## Method

So how do we do it? The method I use2 squashes the image a bit vertically, but overall it looks pretty good for most things. We'll do an example with this input image:

* **Scale:** Scale the image to a 3:2 ratio. Since our images will be squares, this means you simply scale them to 75% width and 50% height. Our example input is 200x200, so we end up with this 150x100 image:

* **Tile:** Place down copies of your scaled image in a 2x2 grid:

* **Crop:** Grab an appropriately sized hexagon from anywhere in this 2x2 grid. Now, for ease of tiling, this hexagon isn't exactly regular. After cropping a square of the original size (here 200x200), you then crop out the corners. The crop lines should run from (roughly) the center of each left/right side to one quarter from the edge on the top/bottom:

And that's your output!

Here's an example of what it might look like when tiled (zoomed out here):

This is code golf, so shortest code in bytes wins. Standard loopholes apply, etc and so on.

---

1 Feel free to believe this or not.
2 Method one from this helpful site.

# Answer
> 10 votes
# Matlab, ~~223 215 209 184~~ 163 bytes

The rescaling is quite straight forward. For cropping the corners I overlay a coordinate system over the pixels, and make a mask via four linear inequalities, which determine the area of the hexagon.

```
l=imread(input(''));
u=size(l,1);
L=imresize(l,u*[2 3]/4);
L=[L,L;L,L];L=L(1:u,1:u,:);
[x,y]=meshgrid(1:u);
r=u/2;x=x*2;
set(imshow(L),'Al',y<x+r&y+x>r&y+x<5*r&y>x-3*r)

```

PS: This turned into a codegolf *nim* game with @MartinBüttner's submission: You alternatingly have to make your code shorter (while providing the same functionality) - the one that can make the last 'shortening' wins=)

# Answer
> 12 votes
# Mathematica, ~~231~~ ~~211~~ ~~209~~ ~~208~~ ~~201~~ ~~188~~ 173 bytes

```
ImageCrop[ImageCollage@{#,#,#,#},e,Left]~SetAlphaChannel~ColorNegate@Graphics[RegularPolygon@6,ImageSize->1.05e,AspectRatio->1]&@ImageResize[#,{3,2}(e=ImageDimensions@#)/4]&

```

This is an unnamed function which takes an image object and returns an image object:

I don't think there's a lot to explain here, but some details which are of note:

* Normally, to tile an image 2x2, you'd use `ImageAssemble[{{#,#},{#,#}}]`, i.e. you hand `ImageAssemble` a 2x2 matrix with copies of the image. However, there's `ImageCollage` which is some sort of magic function which tries to arrange a bunch of pictures as "well" as possible (whatever that means... you can even give the individual images weights and stuff). Anyway, it you give it four images of equal size and with equal (or no) weights, it will also arrange them in a 2x2 grid. That allows me to save some bytes for the nesting of the matrix, as well as the function name.
* The hexagon is rendered as a single polygon via `Graphics`. I'm using the built-in `RegularPolygon@6`, but enforce an aspect ratio of `1` to stretch it as necessary. Unfortunately, `Graphics` needs a couple of expensive options to avoid padding and such, and it also renders black on white instead of the opposite. The result is fixed with `ColorNegate` and then attached to the image's original channels with `SetAlphaChannel`.
* `Graphics` puts a small amount of padding around the hexagon, but we want the alpha hexagon to cover the full size of the cutout. However, `SetAlphaChannel` can combine images of different sizes, by centring them on top of each other and cropping to the smallest size. That means, instead of manually setting `PlotRangePadding->0`, we can simply scale up the hexagon image a bit with `ImageSize->1.05e` (and we need the \`ImageSize option anyway).

# Answer
> 5 votes
# HTML5 + Javascript, 562 bytes

```
<html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",e=>{e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=q=>{l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation="destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4,0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script>

```

Takes input as an image URL via textbox (the URL hopefully counts as a filename). Outputs the data to canvas.

## Version which works across all browsers (580 bytes):

```
<html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",function(e){e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=function(){l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation = "destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4, 0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script>
```

Test it with the "blocks" image from earlier via this URL: https://i.stack.imgur.com/gQAZh.png

# Answer
> 4 votes
# Python 2 + PIL, 320

Reads the name of the image file from stdin.

```
from PIL import ImageDraw as D,Image as I
i=I.open(raw_input())
C=A,B=i.size
i,j=i.resize((int(.75*A),B/2)),I.new('RGBA',C)
W,H=i.size
for a,b in[(0,0),(0,H),(W,0),(W,H)]:j.paste(i,(a,b,a+W,b+H))
p,d=[(0,0),(A/4,0),(0,B/2),(A/4,B),(0,B)],lambda p:D.Draw(j).polygon(p,fill=(0,)*4)
d(p)
d([(A-x,B-y)for x,y in p])
j.show()

```

# Answer
> 2 votes
## PHP, 293 bytes

I've added some newlines for readability:

```
function($t){$s=imagesx($t);imagesettile($i=imagecreatetruecolor($s,$s),$t=imagescale
($t,$a=$s*3/4,$b=$s/2));imagefill($i,0,0,IMG_COLOR_TILED);$z=imagefilledpolygon;$z($i,
[0,0,$s/4,0,0,$b,$s/4,$s,0,$s],5,$f=imagecolorallocate($i,255,0,255));$z($i,[$s,0,$a,
0,$s,$b,$a,$s,$s,$s],5,$f);return$i;}

```

Here is the ungolfed version:

```
function squareToHexagon($squareImage)
{
    $size = imagesx($squareImage);
    $tileImage = imagescale($squareImage, $size * 3/4, $size/2);

    $hexagonImage = imagecreatetruecolor($size, $size);
    imagesettile($hexagonImage, $tileImage);
    imagefill($hexagonImage, 0, 0, IMG_COLOR_TILED);

    $fuchsia = imagecolorallocate($hexagonImage, 255, 0, 255);
    imagefilledpolygon(
        $hexagonImage,
        [
            0,       0,
            $size/4, 0,
            0,       $size/2,
            $size/4, $size,
            0,       $size,
        ],
        5,
        $fuchsia
    );
    imagefilledpolygon(
        $hexagonImage,
        [
            $size,       0,
            $size * 3/4, 0,
            $size,       $size/2,
            $size * 3/4, $size,
            $size,       $size,
        ],
        5,
        $fuchsia
    );

    return $hexagonImage;
}

header('Content-type: image/gif');
$squareImage = imagecreatefrompng('squareImage.png');
$hexagonImage = squareToHexagon($squareImage);
imagegif($hexagonImage);

```

---
Tags: code-golf, graphical-output, image-processing, tiling
---


title: Where is the Arrow Pointing?

text:
# Question
Title: Where is the Arrow Pointing?
# Where is the Arrow Pointing?

In this challenge, your goal is to follow an arrow and output the character it is pointing to.

## Examples

**Input:**

```
d  S------+    b
          |
          |
   c      +--->a

```

**Output:** `a`

---

**Input:**

```
S-----+---a->c
      |
      V
      b

```

**Output:** `b`

The arrow is not pointing at `c` because it is divided by the `a`, meaning this path never leads to an arrow head.

---

**Input:**

```
a S      s
  |      |
  V      V
  b      c

```

**Output:** `b`

---

**Input:**

```
d s<+S+--V
    |||  Q
    -++

```

**Output:** `Q`

This path starts at the `S`, goes down, to the right, goes up, to the right, then points down at the Q. Note that the path does not go straight from `S` to `+`.

---

**Input:**

```
d s-+   +-S  +--+
    +-->b |  |  |
     |  | +--+  |
     +--+ A<----+

```

**Output:** `A`

---

**Input:**

```
S-----+
|     +-^
+---+->B
    +---^

```

**Output:** `B`

Because the valid line will never lead to a whitespace character. The only line that doesn't lead to a whitespace character leads to a `B`

# Challenge

The input will be a multi-line string in which you need to find the character the arrow is pointing at. **There will only be one valid arrow.** The valid arrow will *only* point to alphanumeric characters excluding `S`. A line will never overlap itself. e.g. `-|-`

* `S` (capital) represents where the arrow starts.
* `-` represents a horizontal line
* `+` represents a possible change in axis. A valid arrow will never start with a `+`.
* `|` represents a vertical line
* `> < V ^` any of these represent the arrow head. These will never connect to a `+`.

There will only be one `S` in the string. The input will also be padded to be a rectangle (not necessarily a square).

# Answer
> 9 votes
# JavaScript (ES6), 195 ~~245 231 242 246 250~~

**Edit4** Now, a single recursive function. Probably can't be golfed more

**Edit3** Test for straight line and test for arrowhead merged in T function, S and H functions removed.

**Edit2** Revised and longer :( after this this clarification

**Edit** Small improvements, cutting some char here and there, waiting for CJammers to step in

Test running the snippet below in an EcmaScript 6 compliant browser. (works on Firefox. Chrome still missing the spread operator `...`)

```
f=(s,p=s[I='indexOf']`S`,w=m=[o=~s[I]`
`,1,-o,-1],q,v,r)=>m.some((d,i)=>{for(v=w,q=p;r=s[q+=d],r=='|-'[i&1];)v='+';return r=r==v?f(s,q,v):/\w/.test(r=s[q+m['^>V<'[I](r)]])&&r},s=[...s],s[p]=0)&&r

// Less golfed
// U: recursive scan function
U = (s, // input string or array
     p = s.indexOf`S`, // current position, defult to position of S into string (at first call)
     w = // char to compare looking for a '+', at first call default to garbage as you can't follow '+' near 'S'
       m = [// m, global, offset array form movements.
         o = ~s.indexOf`\n`, // o, global, row line +1 (negated)
         1, -o, -1], // complete the values of m array
     // m and o are assigned again and again at each recursive call, but that is harmless
     // params working as local variables as the function is recursive
     q,v,r) =>
{
   s = [...s]; //convert to array, as I have to modify it while scanning
     //the conversion is done again and again at each recursive call, but that is harmless
   s[p] = 0; // make s[p] invalid to avoid bouncing back and forth

   m.some( // for each direction, stop if endpoint found
      (d,i ) => {
        q = p; // start at current position, then will add the offset relative to current direction
        v = w; // for each direction, assign the starting value that can be '+' or garbage at first call
        // compare char at next position with the expected char based on direction (- for horiz, | for vertical)
        // in m array, values at even positon are vertical movements, odds are horizontal
        while (s[q+=d] == '|-'[i&1]) // while straight direction, follow it until it ends
          v = '+'; // from now on '+' is allowed
        r = s[q];
        if (r == v) // check if found a '+'
          r = U(s, q, v) // recursive call to check all directions from current position
        else
        {
          r = s[q + m['^>V<'.indexOf(r)]], // pointed char in p (if arrowhead, else will return undefined)
          r = /\w/.test(r) && r // if alphanumeric, then we found our result - else r = false
        }
        return r; // returning r to .some; if r is truthy, the .some function will stop
      }
   )
   return r; // result if found, else undefined or null
}

// TEST
out=x=>O.innerHTML+=x.replace(/</g,'<')+'\n'

// Using explicit newlines '\n' to ensure the padding to a rectangle
;[
 ['z<+S-+->a','a']
,['a<-+S>b','b']
,['S-+\n  |\n  V\n  a','a']
,['a S      s\n  |      |\n  V      V\n  b      c  ','b']
,['S-----+  \n|     +-^  \n+---+->B \n    +---^','B']
,['d s<+S+--V\n    |||  Q\n    -++    ','Q']
,['d s-+   +-S  +--+\n    +-->b |  |  |\n     |  | +--+  |\n     +--+ A<----+  ','A']
,['S-----+   \n|     +-^ \n+---+->B  \n    +---^ ','B']
].forEach(t=>{
  r=f(t[0])
  k=t[1]
  out('Test '+(r==k?'OK':'Fail')+'\n'+t[0]+'\nResult: '+ r +'\nCheck: '+k+'\n')
})
```

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

# Answer
> 5 votes
## JavaScript 2016, ~~264 263 249 240 235~~ 234 bytes

Run it in Firefox:

```
m=l=>{o=(q,e)=>q.indexOf(e)
s=[-1,1,c=~o(l,`
`),-c]
f=i=>!o[i]&(!(r=l[i+s[o(a="<>^V",o[i]=c=l[i])]])|r<"0"|r>"z"|r=="S"||alert(s=r))&&c&&[for(j of (c!='+'?a:"")+"-|+")for(k of s)l[i+k]!=j|~o(l[i]+j,k*k>1?"-":"|")||f(i+k)]
f(o(l,'S'))}

```

---

```
m(`d s-+   +-S  +--+
    +-->b |  |  |
     |  | +--+  |
     +--+ A<----+`)

```

---

Scattered in some of my notes:

```
m=l=>{o=(q,e)=>q.indexOf(e) //shorthand for indexOf
s=[-1,1,c=o(l,`
`)+1,-c] // get all possible moves in 1d
w=[] // to keep track of the already-visited indexes
f=i=>{c=l[i] // current character
if(!w[i]&&c) // only continue if the index wasn't already visited and we aren't out of bounds
{r=l[i+s[o(a="<>^V",w[i]=c)]] // sets w[i] to a truthy value and maps the arrows to their corresponding moves in s. If c is an arrow, r is the character it's pointing to.
if(!r||r<"0"||r>"z"||r=="S"||alert(r)) // if r is an alphanumeric character that isn't r, show it and return. If not, continue.
for(j of (c!='+'?a:"")+"-|+") // iterate over all characters to make sure plusses are checked out last, which is necessary at the start.
for(k of s) // check out all possible moves
l[i+k]!=j|| // check if the move leads to the character we're looking for
~o(l[i]+j,k*k>1?"-":"|")|| // make sure the current nor that character goes against the direction of the move
f(i+k)}} // make the move, end of f
f(o(l,'S'))} // start at S

```

# Answer
> 3 votes
**VBA Excel 2007, 894 bytes**

Well this started out a lot better then it ended. I have a feeling my logic is flawed and i could have saved a tonne of bytes if i reordered some of my logic, But Too much time has been sunk into this already =P

The input for this is Column A of whatever sheet you are on. This method uses the fact that Excel has this nice grid and Breaks everything out so you can see what it is doing more clearly.

`Sub m()` is just taking the Copy pasted data from Column A and Breaking it out by char. If We allow a Modified input then if you preformat the maze into 1 char per cell you can save a few bytes by removing `sub m()`

Paste a Maze into Excel any size upto 99 rows by 27 char across. If you want bigger mazes its only 2 extra Bytes to increase the scope to 999 rows and ZZ columns

Also might need a judges call on whether a Excel Sheet is Valid "Standard Input" for a VBA answer. If not, Its pretty much impossible to give VBA Multi-line input VIA the Immediate window

To run this code just paste this code into a Excel module, Paste a maze into A1 and run `sub j()`

```
Sub m()
For k=1 To 99
u=Cells(k,1).Value
For i=1 To Len(u)
Cells(k,i+1).Value=Mid(u,i,1)
Next
Next
Columns(1).Delete
End Sub
Sub j()
m
With Range("A:Z").Find("S",,,,,,1)
h .row,.Column,0
End With
End Sub
Sub h(r,c,t)
If t<>1 Then l r-1,c,1,0,r
If t<>-1 Then l r+1,c,-1,0,r
If t<>2 Then l r,c-1,2,0,r
If t<>-2 Then l r,c+1,-2,0,r
End Sub
Sub l(r,c,y,p,i)
On Error GoTo w
q=Cells(r,c).Text
If q="V" Or q="^" Or q="<" Or q=">" Then
p=1
End If
f="[^V<>]"
If p=1 And q Like "[0-9A-UW-Za-z]" Then
MsgBox q: End
Else
If q="^" Then p=1: GoTo t
If q="V" Then p=1: GoTo g
If q="<" Then p=1: GoTo b
If q=">" Then p=1: GoTo n
Select Case y
Case 1
t:If q="|" Or q Like f Then l r-1,c,y,p,q
Case -1
g:If q="|" Or q Like f Then l r+1,c,y,p,q
Case 2
b:If q="-" Or q Like f Then l r,c-1,y,p,q
Case -2
n:If q="-" Or q Like f Then l r,c+1,y,p,q
End Select
If q="+" And i<>"S" Then h r,c,y*-1
p=0
End If
w:
End Sub

```

# Answer
> 2 votes
# Python 3, 349 bytes

Ugh, so many bytes.

```
S=input().split('\n')
Q=[[S[0].find('S'),0]]
D=[[1,0],[0,1],[-1,0],[0,-1]]
A='-S--++-'
B='|S||++|'
P='>V<^'
i=0
while D:
 a,b=Q[i];i+=1
 j=S[b][a]
 for x,y in D:
  try:
   c,d=a+x,b+y;k=S[d][c]
   if k in P:
    z=P.index(k);print(S[d+D[z][1]][c+D[z][0]]);D=[]
   if (j+k in A and x)+(j+k in B and y)*~([c,d]in Q):Q+=[[c,d]]
  except IndexError: pass

```

Essentially a breadth-first search. Bonus: this actually exits gracefully instead of using `exit()`, which is longer anyway.

# Answer
> 2 votes
# Perl 5

The solution turned out longer than other solutions.
Even after golfing it. So this is the ungolfed version.
It prints the map so that you can follow the cursor.

The way it works? At each step it puts possible moves on the stack. And it keeps on running till there's nothing left on the stack, or a solution is found.
It can be easily modified to find all solutions and choose the nearest --\> while(@\_){...

```
while(<>){
  chomp;
  @R=split//;
  $j++;$i=0;
  for(@R){$nr++;$i++;$A[$i][$j]=$_;if('S'eq$_){$x=$i;$y=$j}}
  $xm=$i,if$xm<$i;$ym=$j;
}
push(@_,[($x,$y,'S',0)]);
$cr='';
while(@_&&''eq$cr){
 @C=pop@_;
 ($x,$y,$d,$n)=($C[0]->[0],$C[0]->[1],$C[0]->[2],$C[0]->[3]);
 $c=$A[$x][$y];
 $A[$x][$y]='.';
 if($c=~m/[S+]/){
    if('L'ne$d&&$A[$x+1][$y]=~m/[+-]/){push(@_,[($x+1,$y,'R',$n+1)])}
    if('D'ne$d&&$A[$x][$y-1]=~m/[+|]/){push(@_,[($x,$y-1,'U',$n+1)])}
    if('R'ne$d&&$A[$x-1][$y]=~m/[+-]/){push(@_,[($x-1,$y,'L',$n+1)])}
    if('U'ne$d&&$A[$x][$y+1]=~m/[+|]/){push(@_,[($x,$y+1,'D',$n+1)])}
 }
 if($c eq'|'){
    if($d ne'U'&&$A[$x][$y+1]=~m/[+|<>^V]/){push(@_,[($x,$y+1,'D',$n+1)])}
    if($d ne'D'&&$A[$x][$y-1]=~m/[+|<>^V]/){push(@_,[($x,$y-1,'U',$n+1)])}
 }
 if($c eq'-'){
    if($d ne'L'&&$A[$x+1][$y]=~m/[+-<>^V]/){push(@_,[($x+1,$y,'R',$n+1)])}
    if($d ne'R'&&$A[$x-1][$y]=~m/[+-<>^V]/){push(@_,[($x-1,$y,'L',$n+1)])}
 }
 if($c=~m/[<>^V]/&&$n<$nr){
    if($c eq'>'&&$A[$x+1][$y]=~m/\w/){$cr=$A[$x+1][$y];$nr=$n}
    if($c eq'<'&&$A[$x-1][$y]=~m/\w/){$cr=$A[$x-1][$y];$nr=$n}
    if($c eq'V'&&$A[$x][$y+1]=~m/\w/){$cr=$A[$x][$y+1];$nr=$n}
    if($c eq'^'&&$A[$x][$y-1]=~m/\w/){$cr=$A[$x][$y-1];$nr=$n}
 }
 print_map()
}
print "$cr\n";
sub print_map {
    print "\033[2J"; #clearscreen
    print "\033[0;0H"; #cursor at 0,0
    for$j(1..$ym){for$i(1..$xm){print (($x==$i&&$y==$j)?'X':$A[$i][$j])}print"\n"}
    sleep 1;
}

```

### Test

```
$ cat test_arrows6.txt
S-----+
|     +-^
+---+->B
    +---^

$ perl arrows.pl < test_arrows6.txt
.-----+
.     +-^
......XB
    .....
B

```

# Answer
> 2 votes
PHP version (comments are french, sorry)

```
<?php
/*
* By Gnieark https://blog-du-grouik.tinad.fr oct 2015
* Anwser to "code golf" http://codegolf.stackexchange.com/questions/57952/where-is-the-arrow-pointing in PHP
*/
//ouvrir le fichier contenant la "carte et l'envoyer dans un array 2 dimmension
$mapLines=explode("\n",file_get_contents('./input.txt'));
$i=0;
foreach($mapLines as $ligne){
    $map[$i]=str_split($ligne,1);
    if((!isset($y)) && in_array('S',$map[$i])){
        //tant qu'à parcourir la carte, on cherche le "S" s'il n'a pas déjà été trouvé.
        $y=$i;
        $x=array_search('S',$map[$i]);
    }
    $i++;
}
if(!isset($y)){
    echo "Il n'y a pas de départ S dans ce parcours";
    die;
}
echo "\n".file_get_contents('./input.txt')."\nLe départ est aux positions ".$map[$y][$x]." [".$x.",".$y."]. Démarrage du script...\n";
$previousX=-1; // Contiendra l'ordonnée de la position précédente. (pour le moment, une valeur incohérente)
$previousY=-1; // Contiendra l'absycede la position précédente. (pour le moment, une valeur incohérente)
$xMax=count($map[0]) -1;
$yMax=count($map) -1;
$previousCrosses=array(); //On ne gardera en mémoire que les croisements, pas l'ensemble du chemin.
while(1==1){ // C'est un défi de codagee, pas un script qui sera en prod. j'assume.
    switch($map[$y][$x]){
        case "S":
            //même fonction que "+"
        case "+":
            //on peut aller dans les 4 directions
            $target=whereToGoAfterCross($x,$y,$previousX,$previousY);
            if($target){
          go($target[0],$target[1]);
            }else{
          goToPreviousCross();
            }
            break;
        case "s":
            goToPreviousCross();
            break;
        case "-":
        //déplacement horizontal
        if($previousX < $x){
          //vers la droite
          $targetX=$x+1;
          if(in_array($map[$y][$targetX],array('-','+','S','>','^','V'))){
        go($targetX,$y);
          }else{
        //On est dans un cul de sac
        goToPreviousCross();
          }
        }else{
          //vers la gauche
          $targetX=$x-1;
          if(in_array($map[$y][$targetX],array('-','+','S','<','^','V'))){
        go($targetX,$y);
          }else{
        //On est dans un cul de sac
        goToPreviousCross();
          }
        }
            break;
        case "|":
        //déplacement vertical
        if($previousY < $y){
          //on descend (/!\ y augmente vers le bas de la carte)
          $targetY=$y+1;
          if(in_array($map[$targetY][$x],array('|','+','S','>','<','V'))){
        go ($x,$targetY);
          }else{
        goToPreviousCross();
          }
        }else{
        //on Monte (/!\ y augmente vers le bas de la carte)
          $targetY=$y - 1;
          if(in_array($map[$targetY][$x],array('|','+','S','>','<','V'))){
        go ($x,$targetY);
          }else{
        goToPreviousCross();
          }
        }
            break;
    case "^":
    case "V":
    case ">":
    case "<":
      wheAreOnAnArrow($map[$y][$x]);
      break;
    }
}
function wheAreOnAnArrow($arrow){
  global $x,$y,$xMax,$yMax,$map;
  switch($arrow){
    case "^":
      $targetX=$x;
      $targetY=$y -1;
      $charsOfTheLoose=array(" ","V","-","s");
      break;
    case "V":
      $targetX=$x;
      $targetY=$y + 1;
      $charsOfTheLoose=array(" ","^","-","s");
      break;
    case ">":
      $targetX=$x + 1;
      $targetY=$y;
      $charsOfTheLoose=array(" ","<","|","s");
      break;
    case "<":
      $targetX=$x - 1;
      $targetY=$y;
      $charsOfTheLoose=array(" ",">","|","s");
      break;
    default:
      break;
  }
  if(($targetX <0) OR ($targetY<0) OR ($targetX>$xMax) OR ($targetY>$yMax) OR (in_array($map[$targetY][$targetX],$charsOfTheLoose))){
      //on sort du cadre ou on tombe sur un caractere inadapté
      goToPreviousCross();
  }else{
    if(preg_match("/^[a-z]$/",strtolower($map[$targetY][$targetX]))){
      //WIN
      echo "WIN: ".$map[$targetY][$targetX]."\n";
      die;
     }else{
      //on va sur la cible
      go($targetX,$targetY);
     }
  }
}
function whereToGoAfterCross($xCross,$yCross,$previousX,$previousY){

            //haut
            if(canGoAfterCross($xCross,$yCross +1 ,$xCross,$yCross,$previousX,$previousY)){
                return array($xCross,$yCross +1);
            }elseif(canGoAfterCross($xCross,$yCross -1 ,$xCross,$yCross,$previousX,$previousY)){
                //bas
                return array($xCross,$yCross -1);
            }elseif(canGoAfterCross($xCross-1,$yCross,$xCross,$yCross,$previousX,$previousY)){
                //gauche
                return array($xCross-1,$yCross);
            }elseif(canGoAfterCross($xCross+1,$yCross,$xCross,$yCross,$previousX,$previousY)){
                //droite
                return array($xCross+1,$yCross);
            }else{
          //pas de direction possible
          return false;
            }
}
function canGoAfterCross($xTo,$yTo,$xNow,$yNow,$xPrevious,$yPrevious){
    global $previousCrosses,$xMax,$yMax,$map;
    if(($xTo < 0) OR ($yTo < 0) OR ($xTo >= $xMax) OR ($yTo >= $yMax)){return false;}// ça sort des limites de la carte
    if(
    ($map[$yTo][$xTo]==" ") // on ne va pas sur un caractere vide
    OR (($xTo==$xPrevious)&&($yTo==$yPrevious)) //on ne peut pas revenir sur nos pas (enfin, ça ne servirait à rien dans cet algo)
    OR (($xTo==$xNow)&&($map[$yTo][$xTo]=="-")) //Déplacement vertical, le caractere suivant ne peut etre "-"
    OR (($yTo==$yNow)&&($map[$yTo][$xTo]=="|")) // Déplacement horizontal, le caractère suivant ne peut être "|"
    OR ((isset($previousCrosses[$xNow."-".$yNow])) && (in_array($xTo."-".$yTo,$previousCrosses[$xNow."-".$yNow]))) //croisement, ne pas prendre une direction déjà prise
   ){
      return false;
    }
    return true;
}
function go($targetX,$targetY){
    global $previousX,$previousY,$x,$y,$previousCrosses,$map;
    if(($map[$y][$x]=='S')OR ($map[$y][$x]=='+')){
        //on enregistre le croisement dans lequel on renseigne la direction prise et la direction d'origine
        $previousCrosses[$x."-".$y][]=$previousX."-".$previousY;
        $previousCrosses[$x."-".$y][]=$targetX."-".$targetY;
    }
    $previousX=$x;
    $previousY=$y;
    $x=$targetX;
    $y=$targetY;
    //debug
    echo "deplacement en ".$x.";".$y."\n";
}
function goToPreviousCross(){
  global $x,$y,$previousX,$previousY,$xMax,$yMax,$previousCrosses;

  /*
  * On va remonter aux précédents croisements jusqu'à ce
  * qu'un nouveau chemin soit exploitable
  */
  foreach($previousCrosses as $key => $croisement){
    list($crossX,$crossY)=explode("-",$key);
    $cross=whereToGoAfterCross($crossX,$crossY,-1,-1);
    if($cross){
      go($crossX,$crossY);
      return true;
    }
  }
  //si on arrive là c'est qu'on est bloqués
  echo "Aucun chemin n'est possible\n";
  die;
}

```

# Answer
> 1 votes
# Haskell, 268 bytes

Congratulations to the Javascripters! Gave up the bounty, but here is what I got. May/Might not work in all cases, but actually handles arrows starting in and arrowheads conncting to `+`es, as far as I know. Didn't even include searching for the `S`, is just `(0,0)` for now.

```
import Data.List
x%m=length m<=x||x<0
a s(x,y)z|y%s||x%(head s)=[]|0<1=b s(x,y)z$s!!y!!x
b s(x,y)z c|g c>[]=filter(>' ')$concat[a s(x+i k,y+i(3-k))k|k<-g c,k-z`mod`4/=2]|0<1=[c]
i=([0,-1,0,1]!!)
g c=findIndices(c`elem`)$words$"V|+S <-+S ^|+S >-+S"
f s=a(lines s)(0,0)0

```

# Answer
> 0 votes
I would like to see an APL version in spirit of https://www.youtube.com/watch?v=a9xAKttWgP4

As a start, a vectorized Julia solution which I think can be translated 1:0.3 to APL or J. It takes a string R representing a L x K arrowgram. It first translates the matrix of symbols into a matrix of small 3x3 matrices whose patterns are the binary expansions of the letters of the string "\0\x18\fH\t\]\]\x1cI". For example '+' is encoded as reshape(\[0,digits(int('\]'),2,8)\],3,3)

```
  0 2 0
  2 2 2
  0 2 0

```

In this representation, the path consists of 2's and gets flooded by 3's from the starting point.

```
A=zeros(Int,L*3+3,K*3+3)
s(i,j=i,n=2)=A[i:end+i-n,j:end+j-n]
Q=Int['A':'Z';'a':'z']
for k=0:K-1,l=0:L-1
r=R[K*l+k+1]
q=search(b"V^><+S|-",r)
d=reverse(digits(b"\0\x18\fH\t]]\x1cI"[q+1],2,8))
A[1+3l:3l+3,1+3k:3k+3]=2*[d;0]
A[3l+2,3k+2]+=r*(r in Q&&r!='V'&&r!='^')+(1-r)*(r=='S')+3(5>q>0)
end
m=0
while sum(A)>m
m=sum(A)
for i=0:1,j=1:2,(f,t)=[(3,6),(11,15)]
A[j:end+j-2,j:end+j-2]=max(s(j),f*(s(j).*s(2-i,1+i).==t))
end
end
for i=[1,4],k=Q
any(s(1,1,5).*s(5-i,i,5).==11*k)&&println(Char(k))
end

```

To test,

```
   R=b"""
       d  S------+    b
                 |
                 |
          c      +--->a
       """;

   K=search(R,'\n') # dimensions
   L=div(endof(R),K)

   include("arrow.jl")

a

```

By the way, I think the clause "Another + may be adjacent but the arrow should prioritize going on a - or | first." puts a vector approach at a disadvantage. Anyway, I just ignored it.

---
Tags: code-golf
---


title: The Black Pawn's Revenge

text:
# Question
Title: The Black Pawn's Revenge
**Objective**

The black pawn wants revenge. Plot out its last attack.

**Rules**

The black pawn (`L`) starts at the top row and moves downwards to the bottom row. Maximise points taken, indicating the path with `X`. Pawns (`P`) are 1, bishops (`B`) and knights (`N`) 3, rooks (`R`) 5, and queens (`Q`) 9. There won't be any kings in the input.

If there is more than one path that has the maximum amount of points, output any of those paths. There will not be any situations where the pawn cannot reach the bottom row.

**Examples**

Input:

```
----L---
-----P--
------P-
--R--P-Q
----P-P-
---P-P-P
--P-N---
-P------

```

Output:

```
----L---
-----X--
------X-
--R--P-X
----P-X-
---P-X-P
--P-X---
-P--X---

```

Input:

```
--L-----
-P------
P-------
-P------
P--Q----
-P------
P-------
-P------

```

Output:

```
--L-----
-PX-----
P-X-----
-PX-----
P--X----
-P-X----
P--X----
-P-X----

```

# Answer
# Python, 332

```
def s(m,l,p):
 if not m:return 1
 b=m[0]+'-';z=filter(lambda i:(b[i]=='-')==(i==l),[l,l-1,l+1])
 if not z:return 0
 g=lambda i:s(m[1:],i,0)+[0,1,3,3,5,9]['-PBNRQ'.index(b[i])];i=max(z,key=g)
 if p:print m[0][:i]+'X'+m[0][i+1:];s(m[1:],i,p)
 return g(i)
import sys
t=sys.stdin.read().split('\n')
print t[0]
s(t[1:],t[0].index('L'),1)

```
> 3 votes

# Answer
# Ruby ~~260 258 255 241 236~~ 222

```
->b{s=->l,w=p{c,*x=l.map &:dup
v=[1,3,3,5,9,0]['PBNRQ'.index(c[y=w||c.index(?L)])||5]
w&&c[y]=?X
(n=x[0])?(m=[]
[y-1,y,y+1].map{|z|(z==y)^(n[z]>?.)&&m<<s[x,z]}
q,r=m.max_by{|m|m ?m[0]:0}
q&&[q+v,c+r]):[v,c]}
s[b.lines][1]}

```

This program defines a function (`s`), which, given some board rows, returns the best path as a string, and the value in points of that path. `s` is recursive, so at each step it evaluates all possibilities and returns the best one.

Here's an online version with tests: http://ideone.com/6eMtm4

The readable version is available here: http://ideone.com/eoXUtp

All the steps I took to reduce the size of the code can be found here.
> 2 votes

---
Tags: code-golf, graph-theory, path-finding, chess
---


title: Koopa Shell Sequence

text:
# Question
Title: Koopa Shell Sequence
In various Super Mario games green and red Koopa Troopa shells can slide frictionlessly on flat surfaces and destroy brick blocks that are in their way. When a shell hits a brick block the block breaks, turning it into empty space, and the Koopa shell reverses direction. As an example, watch the red shell here.

Suppose a Super Mario level is just one block high and every grid cell is either a brick or empty space, except for the leftmost cell which contains a rightward moving shell. The level is also periodic, so if the shell exits the right or left edge of the level it will reenter on the opposite side. In this situation the shell will continue to bounce off of and break all the brick blocks in the level until there are no more. **How far will the shell have traveled just after the last brick block is broken?**

# Challenge

Write a program or function that takes in a non-negative decimal integer. This number, expressed in binary with no leading zeros (the only exception is 0 itself), encodes the one-block-high level layout. A `1` is a brick block and a `0` is empty space.

The Koopa Shell is inserted at the very left edge of the level and is initially moving right. For example, the level associated with input `39` is

```
>100111

```

because `100111` is 39 in binary, and `>` and `<` represent right and left moving shells respectively.

You need to print or return the total distance traveled by the shell once the very last brick block (a.k.a. `1`) has been broken.

The output for `39` is `7` and the changes in the level look like this:

```
Level      Cumulative Distance
>100111    0
<000111    0
>000110    0
0>00110    1
00>0110    2
000>110    3
000<010    3
00<0010    4
0<00010    5
<000010    6
000001<    7
000000>    7  <-- output

```

Similarly, the output for `6` is `1`:

```
Level    Cumulative Distance
>110     0
<010     0
001<     1
000>     1  <-- output

```

**The shortest code in bytes wins.**

For reference, here are the outputs for inputs `0` to `20`:

```
0 0
1 0
2 0
3 0
4 0
5 0
6 1
7 1
8 0
9 0
10 1
11 2
12 2
13 1
14 3
15 3
16 0
17 0
18 1
19 3
20 2

```

And here are the outputs up to input `1000`.

# Answer
# CJam, ~~29~~ ~~26~~ 24 bytes

*Thanks to Sp3000 for saving 3 bytes.*

```
q~2b{_1&}{W\({%}*0+}w],(

```

Test suite. (This prints all results from 0 to the integer given on STDIN.)

## Explanation

This turns the spec on its head a bit: instead of moving the shell through the binary string, we shift and reverse the binary string such that the shell is always at the front, pointing to the right:

```
q~      e# Read and evaluate the input.
2b      e# Convert to base-2 to get the "level".
{_1&}{  e# While there is a 1 in the level...
  W\    e#   Put a -1 below the level.
  (     e#   Pull off the first digit, i.e. the cell the shell is pointing at.
  {     e#   If it's a 1 (i.e. a brick)...
    %   e#     Reverse the level, consuming the -1. This isequivalent to reversing the
        e#     shell in place.
  }*
  0+    e#   Append a zero. If the cell was a brick, this just replaces it with an empty
        e#   cell. Otherwise, this rotates the level by one cell. This is equivalent
        e#   to moving the shell one cell through the periodic level.
        e#   Note that if the leading cell was 0, the -1 remains on the stack.
}w
],(     e# Wrap the stack in an array, get its length and decrement.

```
> 6 votes

# Answer
# Pyth, 24 bytes

```
&.WsH_XZeaYxZ1 0jQ2ssPBY

```

Try it online: Demonstration or Test Suite

The following 22 bytes code should also do the trick. It doesn't work currently, due to a bug in the Pyth compiler.

```
&u_XGeaYxG1ZjQ2)ssPBPY

```

edit: Bug fixed, but of course the solution doesn't count.

Try it online: Demonstration or Test Suite

### Explanation:

Alternating from the front and the back I do the following:

* I search for a 1
* Remember this index by putting it in a list
* Update this 1 to a 0

When there are no 1s left, I calculate the distance. Important is: The shell moves each distance in the list twice (forward and backward), except the last distance.

```
&.WsH_XZeaYxZ1 0jQ2ssPBY   implicit: Y = empty list
                jQ2        convert input number to binary
 .WsH                      start with Z=^;
                           while the sum(Z) > 0, apply the the following to Z:
           xZ1                index of 1 in Z
         aY                   append this to Y
        e                     take the last element of Y (=this index)
      XZ       0              set this 1 (at index ^) in Z to 0
     _                        and revert the order of Z
                           this returns a list of zeros
&                          don't print ^, print the next thing
                     PBY   creates the list [Y, Y[:-1]]
                    s      combine these lists
                   s       sum up the distances

```
> 5 votes

---
Tags: code-golf, game, sequence, base-conversion, binary
---


title: Sourcecode selfie

text:
# Question
Title: Sourcecode selfie
**Objective:**

A guru once said a perfect code selfie is best shot diagonally from upper left corner. A code selfie is almost like a Quine - but rotated 45 degree clockwise. Your mission is to code a program that outputs a code selfie.

**Rules:**

1. You can use any programming language.
2. Your programs should not take any input from file, filename, network or anything else.

**Mandatory criterias:**

Selfies is about the motive and background, so blankspaces (and other not visible content like linefeeds and such) does not count as being part of the character count. All visible characters is restricted to be outputted on the correct 45 degree rotated position while all non-visible characters is not restricted to the correct 45 degree rotated position. Just like a color palette on a normal selfie, mandatory to a code selfie is that it contains atleast 16 of these characters: {a-zA-Z0-9}

**Example:**

If this example is valid sourcecode:

```
Output abcd
Output efgh
Output ijkl
Output mnop

```

The example code should output this:

```
   O
  O u
 O u t
O u t p
 u t p u
  t p u t
   p u t
    u t   a
     t   e b
        i f c
       m j g d
        n k h
         o l
          p

```

This is code-golf, shortest sourcecode in bytes wins!

# Answer
# Javascript (*ES6*), 72 bytes

16 unique alphanumeric character pallete: `fjalert0plcgmixn`

```
(f=j=>alert(`(f=${f})(0)`.replace(/./gmi,x=>' '.repeat(j++)+x+'\n')))(0)
```

`m` and `i` flags are added to the regexp to meet minimum palette requirements.
> 6 votes

# Answer
# CJam, ~~30 28~~ 25 bytes

```
{95c103ic]seeSf.*N*Xmr}_g

```

This is kind of long due to the 16 character from `A-Za-z0-9` limit.

This is a bit non-trivial variant of a standard quine in CJam. Will add explanations soon.

*UPDATE - 2 bytes saved thanks to Martin, 3 bytes saved thanks to Dennis*

Try it online here
> 4 votes

# Answer
# Java, 312

```
class Z{public static void main(String[]a){String s="class Z{public static void main(String[]a){String s=%c%s%1$c,t;for(int i=0,j;i<326;System.out.println(t+s.format(s,34,s).charAt(i++)))for(j=i,t=%1$c%1$c;j-->0;)t+=' ';}}",t;for(int i=0,j;i<326;System.out.println(t+s.format(s,34,s).charAt(i++)))for(j=i,t="";j-->0;)t+=' ';}}

```

There are actually 326 bytes, but if I understand the rules correctly, I don't have to count the 14 spaces.

The program is basically a standard Java quine, plus a lot of whitespace.
> 1 votes

# Answer
# Python 3, 139 characters - 10 spaces = 129 characters

```
sjxd='sjxd=%r;[print(" "*i+(sjxd%%sjxd)[i]) for i in range(len(sjxd%%sjxd))]';[print(" "*i+(sjxd%sjxd)[i]) for i in range(len(sjxd%sjxd))]

```

Since my code was one line, all I had to do was print the program diagonally. My string has the weird name 'sjxd' so that my code could have the 16 unique alphanumeric characters.
> 1 votes

# Answer
# CSS, 69 bytes

```
<style>:before,*{transform:rotate(45deg;display:block;content:'<style>

```

Put in a blank html page to avoid conflict with other tags.

Palette: `stylebfortanm45dgiplck` (22 chars)
> 0 votes

# Answer
# MATLAB, 40 bytes

Bit difficult with the whole recursion thing - how do you print your own source code when adding the code to a string to be printed increases the size of the source code itself. But, never the less, the following will do it:

```
123456;disp(diag('123456;disp(diag())'))

```

The `123456;` bit is there to meet the required 16 unique characters. The following are used:

```
'()123456;adgips

```

The above code doesn't work on Octave for some reason, but does work in MATLAB. Below is the output:

```
1
 2
  3
   4
    5
     6
      ;
       d
        i
         s
          p
           (
            d
             i
              a
               g
                (
                 )
                  )

```

---

Now if you don't mind the `ans=` bit that MATLAB enjoys putting, the following would work for **32 bytes**:

```
12345678;diag('12345678;diag()')

```
> 0 votes

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