text:
Relative vs Absolute
If someone facing north at point A in this grid wanted directions to follow the green path (as they can only follow gridlines) to point B you might tell them:
Go North, North, West, East, East, South, East, East.
or equivalently
Go Forward, Forward, Left, Back, Forward, Right, Left, Forward.
(Where a command of Right, Left, or Back implicitly means turn in that direction, then go forward.)

Write a function with one argument that translates between these absolute and relative directions along the same path, not just to the same point. Assume the directed person always starts facing north.
If the argument is a string of the letters NSEW, return the equivalent relative directions.
e.g. f("NNWEESEE") returns the string FFLBFRLF.
If the argument is a string of the letters FBLR, return the equivalent absolute directions.
e.g. f("FFLBFRLF") returns the string NNWEESEE.
The empty string yields itself. Assume no other input cases.
If your language does not have functions or strings use whatever seems most appropriate.
The shortest code in bytes wins.

Do we assume that a person always start with his head facing North ? That way, in relative terms to go towards East, it would require him to Turn Right, rather than simply saying Forward

@Optimizer Yes, north. And yes to your other point. R equals E at the start.

Yay! You changed your picture to confirm what I always thought!

Are you hooked on PPCG again? ;)

@MartinBüttner Either that or I'm very good at disguising my homework problems. ;)

CJam, 57 53 49
{"NESW""FRBL"_3$&!!:Q$:R^^f#0\{{+0\}Q*_@-R=\}%);}

Previous version
{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}

Example:
{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}:T;
"NNWEESEE"T
N
"FFLBFRLF"T

Output:
FFLBFRLF
NNWEESEE

How it works
{
  "NESW""FRBL"             " Push the two strings. ";
  _3$0=#W>                 " Check if the first character is in FRBL. ";
  :Q                       " Assign the result to Q. ";
  {\}*                     " Swap the two strings if true. ";
  :R;                      " Assign the top string to R and discard it. ";
  f#                       " Find each character of the input in the string. ";
  0\                       " Push a 0 under the top of the stack. ";
  {                        " For each item (index of character): ";
    {                      " If Q: ";
      +0\                  " A B -> 0 (A+B) ";
    }Q*
    _@-                    " C D -> D (D-C) ";
    R=                     " E -> E-th character in R ";
    \                      " Swap the top two items. ";
  }%
  );                       " Discard the last item in the list. ";
}

JavaScript (E6) 84 86 88 92 104
Edit: using & instead of %, different operator precedence (less brackets) and works better with negative numbers
Edit2: | instead of +, op precedence again, -2. Thanks DocMax
Edit3: array comprehension is 2 chars shorter than map(), for strings
F=p=>[o+=c[d=n,n=c.search(i),n<4?4|n-d&3:n=n+d&3]for(i of n=o='',c='NESWFRBL',p)]&&o

Test In FireFox/FireBug console
console.log(F('NNWEESEE'),F('FFLBFRLF'))

Output
FFLBFRLF NNWEESEE

@Optimizer no more. And hoping to shrink even more.

What does && o at the end mean?

@bebe the map function returns an array, inside it, as a side effect, I fill the o string that is what I need to return. array && value evalute to value as any array evaluate to truthy

Finally! I have been staring at this one since it hit 88. Unless I am missing something, you can replace 4+(n-d&3) with 4|n-d&3 and save 2 chars.

C++, 99 97 94 bytes
−3 bytes thans to ceilingcat
The following is formatted as a lambda expression. It takes one char* argument and overwrites it.
[](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;*s++="NESWFRBL"[c|n&3])d+=n=c?*s%11/3-d:n+*s%73%10;}

For those who are not familiar with this feature (like myself 1 hour ago), use it as follows:
#include <iostream>

int main()
{
    char s[] = "NNWEESEE";
    auto x = [](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;d+=n)c?n=*s%11/3-d:n+=*s%73%10,*s++="NESWFRBL"[c|n&3];};

    x(s); // transform from absolute to relative
    std::cout << s << '\n';

    x(s); // transform from relative to absolute
    std::cout << s << '\n';
}

Some explanations:

When using code like flag ? (x = y) : (x += z), the second pair of parentheses is required in C. So I used C++ instead!
C++ requires specifying a return type for a function. Unless I use a lambda expression, that is! An added bonus is I don't need to waste 1 character on the name of the function.
The code *s*9%37&4 tests the first byte; the result is 4 if it's one of NESW; 0 otherwise
The code *s%11/3 converts the bytes NESW to 0, 1, 2, 3
The code *s%73%10 converts the bytes FRBL to 0, 9, 6, 3 (which is 0, 1, 2, 3 modulo 4)
When converting relative directions to absolute, I don't need the d variable. I tried rearranging code to eliminate it completely, but it seems impossible...

I like the way your convert the letters to numbers very much. :)

APL, 72
{^/⍵∊A←'NESW':'FRBL'[1+4|-2-/4,3+A⍳⍵]⋄A[1+4|+\'RBLF'⍳⍵]}

If the interpreter configurations can be changed without penalty, then score is 66, by changing ⎕IO to 0:
{^/⍵∊A←'NESW':'FRBL'[4|-2-/0,A⍳⍵]⋄A[4|+\'FRBL'⍳⍵]}

Python, 171 139
No way near as short as the other solutions, but I guess it should be relatively good for what can be done with Python:
def f(i):a,b='NWSE','FLBR';I=map(a.find,'N'+i);return''.join((b[I[k+1]-I[k]],a[sum(map(b.find,i)[:k+1])%4])[-1in I]for k in range(len(i)))

Expanded version for slightly better readability:
def f(i):
    a, b = 'NWSE', 'FLBR'
    I = map(a.find,'N'+i)     # translate to numbers assuming abs. directions
    J = map(b.index,i)        # translate to numbers assuming rel. directions
    if not -1 in I:
        o = [b[I[k+1]-I[k]] for k in range(len(i))]    # rel. dir. is differences of abs. dir.
    else:
        o = [a[sum(J[:k+1])%4] for k in range(len(i))] # abs. dir. is sum of all rel. dir. so far
    return ''.join(o)

GNU sed, 356 bytes
The challenge calls for a simple transformation on a stream of characters.  sed, the stream editor is the obvious choice of language ;-)
/[FRBL]/bx                                     # Jump to label x if relative
:y                                             # label y (start of abs->rel loop)
/[FRBL]$/q                                     # quit if string ends in rel char
s/(^|[FRBL])N/\1F/;ty                          # Substitute next abs char with
s/(^|[FRBL])E/\1R/;tr                          #     rel char, then jump to
s/(^|[FRBL])S/\1B/;tb                          #     relevant rotation label if
s/(^|[FRBL])W/\1L/;tl                          #     a match was found
by                                             # loop back to y
:r;y/NESW/WNES/;by                             # Rotation labels: transform then
:b;y/NESW/SWNE/;by                             #     loop back to y
:l;y/NESW/ESWN/;by
:x                                             # label x (start of rel->abs loop)
/^[NESW]/q                                     # quit if string starts w/ abs char
/F([NESW]|$)/s/F([NESW]|$)/N\1/                # Matches for each direction:
/R([NESW]|$)/y/NESW/ESWN/;s/R([NESW]|$)/E\1/   #     rotate, then substitute
/B([NESW]|$)/y/NESW/SWNE/;s/B([NESW]|$)/S\1/
/L([NESW]|$)/y/NESW/WNES/;s/L([NESW]|$)/W\1/
bx                                             # loop back to x

(Comments and spaces stripped for the purposes of golf score calculation)
Output:
$ sed -rf absrel.sed <<< NNWEESEE
FFLBFRLF
$ sed -rf absrel.sed <<< FFLBFRLF
NNWEESEE
$

Explanation:
The idea here is that when we change the frame of reference, there is always a direct mapping between {N, E, S, W} and {F, R, B, L}.
In the case of absolute to relative, we work fowards through the string.  For each character we map {N, E, S, W} to {F, R, B, L}, then rotate the remaining [NESW] characters according to the character we just mapped, then move onto the next character.
For the case of relative to absolute we do the reverse.  We work backwards through the string, rotating all following [NESW] characters according to the character immediately in front.  Then we map that character {N, E, S, W} to {F, R, B, L}, until we get to the start of the string.

Go, 201
type q string;func F(s q)q{d,z:=byte(0),make([]byte,len(s));for i,c:=range[]byte(s){if(c^4)*167%3<2{c=c*156%5;z[i],d="LBRF"[(d-c)%4],c-1;}else{c=(c^43)*3%7-1;d=(d+c)%4;z[i]="NESW"[d];};};return q(z);}

Readable version:
func F(s string) string {
    d, z, R, A := 0, make([]byte, len(s)), "LBRFLBR", "NESW"
    for i, c := range []byte(s) {
        switch c {
        case 'N': c = R[d+3]; d = 0
        case 'E': c = R[d+2]; d = 1
        case 'S': c = R[d+1]; d = 2
        case 'W': c = R[d]; d = 3
        case 'F': c = A[d]
        case 'R': d = (d + 1) % 4; c = A[d]
        case 'B': d = (d + 2) % 4; c = A[d]
        case 'L': d = (d + 3) % 4; c = A[d]
        }
        z[i] = c
    }
    return string(z)
}

Haskell, 224
import Data.Function
i=flip(\x->length.takeWhile(/=x))
r=['F','R','B','L']
a=['N','E','S','W']
f s@(x:_)|elem x a=map((r!!).(`mod`4).(4-))$zipWith((-)`on`(i a))('N':s)(s)|True=tail$map((a!!).(`mod`4)).scanl(+)(0)$map(i r) s

This assigns rotation numbers to the relative directions, and orientation numbers to the absolute directions, then either finds the rotations between successive orientations or the orientations after successive rotations. The i function finds the index within the two legends.


text:
Shortest code to find next prime palindrome
I was trying to find the shortest code possible that given a number n, returns the next prime palindrome number (limited to below 100000). If the number itself is a prime palindrome, the code should return the next one.
Write the shortest program/function that, when given an input n (less than 100000), returns the next palindromic prime number.
This is an example working program:
def golf(n):
    n+=1
    while str(n)!=str(n)[::-1] or not all(n%i for i in xrange(2,n)):n+=1
    return n

This seems more like a general request which are meant for Stack Overflow. This site is more of a programming contest. But I can easily see this as a contest, give you remove the limitation of Python language and add the [tag:code-golf] tag

Do you copy ????

I edited your question to make it into a valid contest here. If you really just wanted to know how to shorten your code, that is not for this site.

ok thanks for the clarification. I will remove the limitation of Python

The "working program" doesn't work. The value s will never change.

True. I'll edit that.

Can we assume that n is a positive integer?

yes you can assume that

You forgot a def before golf(n).

tue. needless to say my example code was horribly wrong! i'll edit it

CJam, 15 bytes
li{)__mfsW%i^}g

Reads a single, positive integer from STDIN. Try it online.
Example run
$ cjam <(echo 'li{)__mfsW%i^}g') <<< 250
313

How it works
This uses a tricky prime check instead of the built-in mp:
15 mf, for example, pushes [3 5]. We cast to a string ("35"), reverse that string ("53"), cast to integer (53) and XOR the result with the original integer (22). Since the result in non-zero, 35 is not a palindromic prime.
li                 " N := int(input())        ";
  {          }g    " While R:                 ";
   )               "   N += 1                 ";
     _mfs          "   R := str(factorize(N)) ";
         W%i       "   R := int(reverse(K))   ";
    _       ^      "   R ^= N                 ";

0 and 1 aside (which are non-issues if the input is a positive integer), I'm confident that the code will work. I'm currently running a brute-force search for false positives.

Verfied by brute force for all unsigned 32-bit integers.

Brachylog, 4 bytes
<.ṗ↔

Try it online!
Simple and neat.
?<.ṗ↔.     (Initial ? and final . are implicit)
?<.        Input is less than the output
  .ṗ       Output is a prime number
    ↔.     And output reversed is the output itself (it is a palindrome)

CJam, 18 17 characters
ri{)__s_W%=*mp!}g

How it works:
ri                     "Convert the input into an integer";
  {            }g      "Run this code block while the top stack element is truthy";
   )__                 "Increment the number and make two copies";
      s_               "Convert one of them to string and take another copy";
        W%=            "Reverse the last string and compare with second last";
           *           "If they do not match, make the second last number 0";
            mp!        "Put 1 to stack if number is not prime, continuing the loop";

Try it online here

Python, 63 60 characters
def g(n):
 n+=1
 while`n`[::-1]!=`n`or~-2**n%n>2:n+=1
 return n

This can be 2 bytes shorter as a recursive function: Try it online!

Mathematica - 75 characters
i=IntegerDigits;f@n_:=Select[Range[n+1,10^5],i@#==Reverse@i@#&&PrimeQ@#&,1]

Ungolfed:
i=IntegerDigits;
f@n_:=Select[
  Range[n+1,10^5],
  i@#==Reverse@i@#
  &&
  PrimeQ@#
  &,
  1
]

Sets an alias for the IntegerDigits function, then defines a function which selects the first number on the list of n+1 to 100,000 which satisfies PrimeQ and has palindromic digits.  The function is called f@50000, returning {70207}.

Haskell - 71
p n|s==reverse s&&all((/=0).mod m)[2..n]=m|1<2=p m where m=n+1;s=show m

Ungolfed
nextPrime n
  | s == reverse s && all ((/=0).(mod m)) [2..n] = m
  | otherwise = nextPrime (n + 1)
  where
    m = n + 1
    s = show m

Pyth, 17
~Q1Wn`Q_`ePQ~Q1)Q

Explanation:
                         Implicit: Q = eval(input())
~Q1                      Q +=1
W                        while
 n                       not equal
  `Q                     repr(Q)
    `ePQ                 repr(end(prime_factorization(Q)))
 ~Q1                     Q += 1
)                        end while
Q                        print(Q)

Ruby, 63
require"prime"
x=->n{Prime.find{|p|q=p.to_s;p>n&&q.reverse==q}}

Explanation

Input is taken as the arguments to a lambda. It's expected to be an Integer.
Prime is Enumerable. Use Enumerable#find to find the first prime that's bigger than the input and is equal to itself when reversed.

K (oK), 27 bytes
{~(x=.|$x)&/(2_!x)!'x}(1+)/

Try it online! for all test cases where the input n<1000
My first answer in K. Yay!
Thanks to @ngn for the help.
ngn also found a shorter solution which is very wasteful. Times out on TIO for n>919.
{x+(~x=.|$x)|/x=*/!2#x}/

How?
{~(x=.|$x)&/(2_!x)!'x}(1+)/    # Main function f, argument x
 ~                             # Not
  (x=.|$x)                     # x equals the inverse of x (is a palindrome)
          &/                   # And reduction; will return truthy iff all
                               # results in the list are truthy (not 0)
            (2_!x)             # range [2..x]
                  !'x          # each modulo x
{                    }(1+)/    # While loop with x+1; returns x implicitly.

Japt, 11 bytes
_¥sÔ©Zj}aUÄ

Run it online

JavaScript (E6) 95
Q=n=>(f=>{for(;a=!f;)for(f=++n==[...n+''].reverse().join('');b=n/++a|0,f&&a<=b;)f=a*b-n;})(0)|n

Ungolfed
Q=n=>
{
  for (f=0; !f;) // loop until both palindrome and prime
  {
    f = ++n == [...n+''].reverse().join(''); // palindrome check
    if (f) // if palindrome, check if prime
      for(a = 1; b=n/++a|0, f && a<=b; )
        f = a*b-n;
  }
  return n
}

Test In FireBFox/FireBug console
for (o=[],i=9;i<100000;)o.push(i=Q(i));console.log(o)

Output
[11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689, 1003001]

05AB1E (legacy), 9 bytes
[>ÐÂQsp*#

Try it online or verify some test cases.
Explanation:
             # (Implicit input)
             #  i.e. 15
             #  i.e. 130
[            # Start an infinite loop
 >           #  Increase the top of the stack by 1
             #   i.e. 15 + 1 → 16
             #   i.e. 100 + 1 → 101
  Ð          #  Triplicate that value
   Â         #  Bifurcate it (short for Duplicate & Reverse)
             #   i.e. 16 → 16 and '61'
             #   i.e. 101 → 101 and '101'
    Q        #  Check if it's equal (this checks if the number is a palindrome)
             #   i.e. 16 and '61' → 0 (falsey)
             #   i.e. 101 and '101' → 1 (truthy)
     s       #  Swap so the value is at the top of the stack again
      p      #  Check if it's a prime
             #   i.e. 16 → 0 (falsey)
             #   i.e. 101 → 1 (truthy)
       *     #  If it's both a palindrome and a prime:
             #    i.e. 0 and 0 → 0 (falsey)
             #    i.e. 1 and 1 → 1 (truthy)
        #    #   Stop the infinite loop
             # (Implicitly outputs the resulting value)

05AB1E, 7 bytes
[ÅNDÂQ#

Try it online!
[ÅNDÂQ#  # full program
      #  # exit...
[        # infinite loop...
      #  # when...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    ÂQ   # is equal to...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    Â    # reversed
         # (implicit) exit infinite loop
   D     # implicit output

Raku, 37 bytes
{first &is-prime&{.flip eq$_},$_^..*}

Try it online!
The outer expression is first EXPR, $_ ^.. *, which looks for the first number which matches EXPR in the numbers from one greater than the input argument $_ to infinity.  (The caret ^ in front of the .. means to exclude the starting point from the range.)
EXPR is an and-junction of two function, the built-in &is-prime and the anonymous function { .flip eq $_ }, which tests for palidrome-ness.  A number matches this junction only if it matches both members.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Restricted Polyglot
Polyglots are programs that are valid in multiple programming languages simultaneously. Most such polyglots are written in such a way that certain constructs of one language are interpreted as comments of another language (e.g. #define in C being interpreted as a comment in several scripting languages).
I am curious to see if it is possible to make a non-trivial polyglot which contains no comments, but also immediately changes when you remove any non-whitespace character,  I therefore challenge you to come up with such a program.
The concrete rules are as follows:

(Output). Your program must produce some output on the console under each of your languages. That is, your program is not permitted to simply exit without printing anything.
(Variance). As a relaxation of the standard polyglot definition, the program's output may vary between languages.
(Errors). Your program must not produce any errors (broadly defined) under any of your languages. For most languages, this is defined as returning a non-zero exit code from the compiler and/or interpreter.
(Restriction). The removal of any single non-whitespace character from your code should cause your program to change its behaviour under every one of your languages. The program may "change" by becoming invalid for that language, or by changing the output that is produced.
This is a code challenge. Winner is the program which is valid in the most programming languages. Ties will be broken in favor of shorter program length.

The restriction rule doesn't apply to the removal of several characters. That is, it is fine if removing several characters simultaneously results in no change for one of your languages.
Observe that the restriction rule implies that you cannot use Whitespace as one of your languages, as removing any non-whitespace character won't change the behaviour of the Whitespace program.
Here's a simple example of a program that fulfills all the above restrictions, for the languages Python 2 and Python 3:
print("Hello World!")

Removing any character in print will cause both languages to throw a NameError; removing any bracket or quote will throw a SyntaxError, and removing any of the string characters will change the output in both languages. (Note that print("hello", "world") is a more subtle, but still valid program under the above rules).
This example is a bit lame because Python 2 and Python 3 are very similar, so I won't accept any other solutions that only use different versions of the same language (especially Python 2 and Python 3).

@IngoBürk: The rule prevents you from writing a functional polyglot which involves Whitespace, unless somehow your other language is also whitespace-only.

FWIW your example, print("Hello World!") is also valid Ruby code

It's a little annoying that the simple answers (like mine) to a [polyglot] tend to be able to have so many languages.

To avoid the myriad language variants or languages with similar syntax, it would be more interesting to require that two languages count as different only if the program produces different output.

Bash + GolfScript + CJam
"echo" []
{ cat<&3;} \
3<""<("echo" 'p'~)

Output
Bash:
[]
p~

GolfScript:
"echo"
echo{ cat<&3;}0

CJam:
echo{ cat<&3;}-1echop

There is a \x7f in the end of output of CJam.

...wait, how does this work in all three languages, without being redundant?

@nneonneo It simply prints all the unused code in other languages.

Bash + Befunge
"echo" $,$,"ol":,,,@

prints 'hello' in befunge.

I can attest that every character (except the space) does something in Befunge. I can't do so for the Bash though. This is impressive.

bc, GolfScript, Homespring, huh, Octave, Scilab (0 bytes)

Guaranteed to comply with rule 4. Not a winner, but would do well in the tie break.
Output
bc
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

GolfScript

Homespring
In Homespring, the null program is not a quine.

huh
?

Octave
GNU Octave, version 3.6.4
Copyright (C) 2013 John W. Eaton and others.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  For details, type `warranty'.

Octave was configured for "x86_64-redhat-linux-gnu".

Additional information about Octave is available at http://www.octave.org.

Please contribute if you find this software useful.
For more information, visit http://www.octave.org/get-involved.html

Read http://www.octave.org/bugs.html to learn how to submit bug reports.

For information about changes from previous versions, type `news'.

Scilab
Startup execution:
  loading initial environment

-->

I know there's an esolang which specifically prevents 0 length quines by doing this sort of thing (oh wait, that's Homespring). I believe huh? outputs something.

Thanks! Sadly, I can't convince huh? to run on Linux...

Sadly, I deleted the interpreter from my computer, and I can't download the interpreter on this network.

All I needed was an extra package for mono. Your program prints What?\n?, by the way.

Also works in GNU Make (if that's a programming language): make: *** No targets.  Stop.

@user23013: Makefiles are Turing complete, so I'd say yes. Thanks! (The output is entirely different on my system.)

@Dennis The correct way running a file called polyglot should be make -f polyglot. Or you can simply rename that file to Makefile and then make.

@user23013: Right. In that case, it's not a valid entry, since make's exit code is 2.

@Dennis Ah... make -f polyglot some_existed_file works, but I don't think that should qualify...

Also works in Guile, at least if you pipe it in on standard input; my version prints a prompt and then exits. Apparently it can't tell that it isn't being used interactively.

GolfScript + PHP + CJam + Mathematica + bc + Pyth + /// + TI-Basic + R + Octave + Matlab + Scilab + Numeric Topline + ?Fueue + huh?
10

In Golscript, PHP, CJam, Mathematica, bc, Pyth, ///, and TI-Basic, it outputs 10.
In R, it outputs [1] 10
In Octave, it outputs ans =  10
In Matlab and Scilab, it outputs ans = 10.
In Numeric Topline, it outputs 0.
If I understand Fueue properly, it outputs a newline, then acts as a cat program.
In huh?, it outputs
What?
?

Also works in CJam

I don't think interactive interpreters should count.

This runs fine in a lot of languages, but doesn't provide output in that many...

This is also valid in HTML, bc, Matlab and Scilab. If you change 72 to 10, it should print 0 in Numeric Topline.

HTML is not a programming language according to the meta discussion as it has no means of simple arithmetic or loops.

bc prints 10 on my machine. Matlab and Scilab prints ans = 10 (and possibly some whitespace).

And in mathematica it should output 10

Outputs 10 in Pyth

It also seems to be valid in ///.

Should work in Javascript too..

@TejasKale That only works in a JavaScript interpreter, such as the Chrome Console. But the standard for this website is that JavaScript needs to be wrapped in alert for it to be valid. Same with Python, we aren't allowed to simply post 10 as a quine in Python.

This does "work" in nodejs, but prints nothing(same for python). Reading the rules again, I see why these languages were not included.

TI-BASIC it outputs 10.

@IngoBürk HTML + CSS is turing complete and therefore can perform arithmetic, (it essentially can emulate rule 110)

Seems like this answer is not fully correct.
  I partially fixed it, and going to improve the other part in a few days.

C++ & Javascript
The idea is:
void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(){};int=0");
int
main()
{
puts("Hi from C++!");
}

C++: http://codepad.org/SK2wbIDL
Javascript: Just copy code to the browser console
And a set of fixes to make it satisfy

(Restriction). The removal of any single non-whitespace character from your code should cause your program to change its behaviour under every one of your languages. The program may "change" by becoming invalid for that language, or by changing the output that is produced.

From Javascript side:
Changing int, main or puts will crash with reading of undeclared variable. But bool and Hi from C++! can be safely changes. Let's fix it:
puts=function(){}

puts=function(s){s=='Hi from C++!'?bool:nope}

If strings are equal, it checks existance of bool, otherwice it crashes with undeclared nope.
Now, there are 2 trailing semicolons that can be removed. The first is fixed esyly - just remove newline before int:
void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(){};int=0");int

The second is before }, so I need some constriction, valid in both languages and not requiring semicolon at the end in C++ or forsing a semicolon in js. Fine:
while(0);

It's impossible to omit semicolon in js as while needs the body.
So the program at the moment is:
void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(s){s=='Hi from C++!'?bool:nope};int=0");int
main()
{
puts("Hi from C++!");while(0);
}

From C++ side:
There are 2 problems: eval can have any name and all js code can be changed.
I'll try to fix them in a few days.

JavaScipt, Lua, R and Python 3 - 24 bytes
May work on some other languages, I'll test latter.
alert=print;alert(1)

JavaScript was tested on Firefox's console and the other languages here, here and here

This does not work in Javascript. It shows the print dialog.

CJam + Golfscript
Okay, this is somewhat boring, but it's a start.
1,

Prints "0" in both languages. Removal of the 1 causes an error, removing the , prints "1" instead.
The same can be done with 1) or 1(. There are many alternatives.
(Yes, I know this isn't code-golf)

C and C++
#include <stdio.h>
int main() { puts("Hello!"); return 0; }

C and C++ are different languages that are almost compatible with each other - contrary to what you might hear C++ is not a superset of C.  Look at http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B for some differences.  The example above is not idiomatic C++ but it does work and produces the same output in both C and C++.

You can remove the 0 for C.

@Dennis Not in C89.

@Gilles: If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined. (The C89 Draft - 2.1.2.2 Hosted environment) That doesn't make the program invalid nor does it change its output, so for the purposes of this question, the 0 can be removed.

@Dennis I think an unspecified exit code counts as making the program invalid as per the rules of this question. If it doesn't, make that a C89 implementation where this program returns a nonzero exit code, such as gcc -ansi on x86 (or many other architectures: what happens is that the return value of puts ends up being in the register where the runtime reads the value to return from the main function).

@Gilles: My interpretation of rule 3 is that the compiler must return 0, not the program.

Perl + Ruby + Python
I think in PHP this would need a semicolon if you are running with -R.
print "Hello World!"

This works in Python as well.

Also works with Lua.

Bash + sh + zsh + ksh, 4 bytes:
echo

Really simple and satisfies every rule:

Outputs a newline in each of the languages.
Output currently does not vary in any way between the languages.
Does not produce an error in any of the languages...
...except when any of the characters are removed/changed.

Bash + sh + zsh + ksh + Windows Batch, 4 bytes:
echo

Really simple and satisfies every rule:
Outputs a newline which doesn't vary in each of the languages (but Windows Batch, which outputs ECHO is on, on the language you use), doesn't error, except when any letter is removed or changed.

Your answer appears to be almost identical to this one: https://codegolf.stackexchange.com/a/100654/65326

Every single flavor of HQ9+, 1 byte
9

Including but not limited to HQ9+, FishQ9+, BrainfishQ9+, CHIQRSX9+, Unified HQ9+, H9+, HQ9++,HQ9+-, FHQ9+-, HQ9F+, HQ9+B, HQ9+~, HQ9+2D, HI9+, and probably some more that I've missed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Subdivide-Sum Sequence
Consider the digits of any integral base above one, listed in order. Subdivide them exactly in half repeatedly until every chunk of digits has odd length:
Base    Digits              Subdivided Digit Chunks
2       01                  0 1
3       012                 012
4       0123                0 1 2 3
5       01234               01234
6       012345              012 345
7       0123456             0123456
8       01234567            0 1 2 3 4 5 6 7
9       012345678           012345678
10      0123456789          01234 56789
11      0123456789A         0123456789A
12      0123456789AB        012 345 678 9AB
...
16      0123456789ABCDEF    0 1 2 3 4 5 6 7 8 9 A B C D E F
...

Now, for any row in this table, read the subdivided digit chunks as numbers in that row's base, and sum them. Give the result in base 10 for convenience.
For example...

for base 3 there is only one number to sum: 0123 = 123 = 510
for base 4 there are 4 numbers to sum: 04 + 14 + 24 +  34 = 124 = 610
base 6: 0126 + 3456 = 4016 = 14510
base 11: 0123456789A11 = 285311670510

Challenge
Write a program that takes in an integer greater than one as a base and performs this subdivide sum procedure, outputting the final sum in base 10. (So if the input is 3 the output is 5, if the input is 6 the output is 145, etc.)
Either write a function that takes and returns an integer (or string since the numbers can get pretty big) or use stdin/stdout to input and output the values.
The shortest code in bytes wins.
Notes

You may use any built in or imported base conversion functions.
There is no upper limit to the input value (besides a reasonable Int.Max). The input values don't stop at 36 just because "Z" stops there.

p.s. this is my fiftieth question :)

if I use a function, what meaning "..the final sum in base 10" mean? if we return the output, then it's represented internally in the computer in binary. what does "in base 10" mean there?

Congratulations on reaching 50 questions.  And such an astonishing variety. Thanks.

@proudhaskeller In that case just give your examples in base 10 if you have any. Though it's also alright if the function returns a string since the numbers can be quite large. Then uses base 10.

CJam, 17 15
q5*~W*&/\,/fb:+

Works if there is a trailing newline in the input.
A more obvious version for those who don't know x & -x:
q5*~(~&/\,/fb:+

How it works
q5*~               " Push 5 times the input as numbers. ";
W*&/               " Calculate n / (n & -n). (Or n / (n & ~(n-1))) ";
\,                 " List the digits. ";
/                  " Split into chunks. ";
fb:+               " Sum in the correct base. ";

Getting the highest power of 2 as x & -x is really clever.

Accepting this since it is the shortest, but props to Ell for finding a formula.

Python, 82 78
def f(b):G=b^b&b-1;return sum(b**(b/G-i-1)*(G*i+(G-1)*b/2)for i in range(b/G))

Huh?

The number of digit groups that the subdivison yields, G, is simply the greatest power of two that divides the number of digits (i.e. the base), b.
It's given by G = b ^ (b & (b - 1)), where ^ is bitwise-XOR.
If you're familiar with the fact that n is a power of two iff n & (n - 1) = 0 then it should be pretty easy to see why.
Otherwise, work out a few cases (in binary) and it'll become clear.

The number of digits per group, g, is simply b / G.

The first digit group, 012...(g-1), as a number in base b, is .

The next group, g(g+1)...(2g-1), as a number in base b, is the sum
.

More generally, the n-th group (zero-based), as a number in base b, an, is .

Recall that there are G groups, hence the sum of all groups is

which is what the program calculates.

Wow, that is super, how did you figure that formula out ? Mind if I convert this to CJam ?

@Optimizer Go ahead! I'll write an explanation when I have some more time.

+1 if you are still like "Huh?" after reading that explanation :D

Just to be clear, not because there is any fault in explanation, but because its too complex for my brain :D

That is magic! You can save some chars by using ~: b/G-i-1 can be b/g+~i and (G-1)*b/2 can be ~-G*b/2

@xnor Good ones! Though at this point I think it'll only obfuscate the code more than it already is while there are already much shorter submissions.

Haskell, 74 69 55
f n=sum[(n-x)*n^mod(x-1)(until odd(`div`2)n)|x<-[1..n]]

examples:
*Main> map f [2..15]
[1,5,6,194,145,22875,28,6053444,58023,2853116705,2882,2103299351334,58008613,2234152501943159]

CJam (snapshot), 19 bytes
li__,\mf2m1+:*/fb:+

Note that the latest stable release (0.6.2) has a bug that can cause mf to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (:i).
To run this with CJam 0.6.2 (e.g., with the online interpreter), you have to use the following code:
li__,\mf:i2m1+:*/fb:+

Alternatively, you can download and build the latest snapshot by executing the following commands:
hg clone http://hg.code.sf.net/p/cjam/code cjam-code
cd cjam-code/
ant

Test cases
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 3; echo
5
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 4; echo
6
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 6; echo
145
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 11; echo
2853116705

How it works
li                     " N := int(input()) ";
   _,                  " A := [ 0 1 ... (N - 1) ] ";
  _  \mf               " F := factorize(N) ";
        2m1+           " F := F - [2] + [1] ";
            :*         " L := product(F) ";
              /        " A := A.split(L) ";
               fb      " A := { base(I, N) : I ∊ A } ";
                 :+    " R := sum(A) ";

CJam, 41 bytes
This is basically Ell's solution in CJam:
ri:B__(^2/):G/,{_BBG/@-(#G@*G(B2/*+*}/]:+

Try it online here

My original submission:
Doesn't work correctly for base 11 and above
ri:B2%BB{2/_2%!}g?B,s/:i:+AbBb

Will try to see if I can get it to work for base 11 and above, without increasing the size much.

Mathematica, 114 bytes (or 72 bytes)
Hm, this got longer than I thought:
f@b_:=Tr[#~FromDigits~b&/@({Range@b-1}//.{a___,x_List,c___}/;EvenQ[l=Length@x]:>Join@@{{a},Partition[x,l/2],{c}})]

And ungolfed:
f@b_ := Tr[#~FromDigits~
     b & /@ ({Range@b - 1} //. {a___, x_List, c___} /;
       EvenQ[l = Length@x] :> Join @@ {{a}, Partition[x, l/2], {c}})]

Alternatively, if I just port Ell's nifty formula, it's 72 bytes:
f=Sum[#^(#/g-i-1)(g*i+(g-1)#/2),{i,0,#/(g=Floor[BitXor[#,#-1]/2+1])-1}]&

J - 22 char
Function taking a single argument (call it y for the purposes of this golf) on the right.
+/@(#.i.]\~-%2^0{1&q:)

First we use 1&q: to get the number of times y is divisible by 2, and then divide -y by 2 that many times. This gives us the negative of the width that we need to split things into, which is perfect, because ]\ will take overlapping pieces if the argument is positive, and non-overlapping if it's negative.
So then we split up i.y—the integers from 0 to y-1—into vectors of these widths, and use #. to convert them from base y to base 10. Finally, +/ does the summing, and we're done.
Examples: (input at the J REPL is indented, output is flush left)
   +/@(#.i.]\~-%2^0{1&q:) 6
145
   f =: +/@(#.i.]\~-%2^0{1&q:)
   f 11
2853116705
   (,: f every) 1+i.14   NB. make a little table for 1 to 14
1 2 3 4   5   6     7  8       9    10         11   12            13       14
0 1 5 6 194 145 22875 28 6053444 58023 2853116705 2882 2103299351334 58008613
   f every 20 30 40x     NB. x for extended precision
5088086 7455971889417360285373 368128332
   ":"0 f every 60 240 360 480 720 960x   NB. ":"0 essentially means "align left"
717771619660116058603849466
3802413838066881388759839358554647144
37922443403157662566333312695986004014731504774215618040741346803890772359370271801118861585493594866582351161148652
256956662280637244030391695293099315292368
2855150453577666748223324970642938808770913717928692581430408703547858603387919699948659399838672549766810262282841452256553202264
17093564446058417577302441219081667908764017056

JavaScript, 99 89  bytes
function f(n){m=n/(n&-n);for(r=s=i=0;;){if(!(i%m)){r+=s;s=0;if(i==n)return r;}s=s*n+i++}}

or
function g(n){c=n&-n;for(s=i=0;i<n/c;++i)s+=Math.pow(n,n/c-i-1)*(c*i+(c-1)*n/2);return s}

The second function is similar to Ell's one. The first one uses a more traditional approach. Both are 89 characters in size.
Try here: http://jsfiddle.net/wndv1zz8/1/

Jelly, 10 9 bytes
Ḷœs&N$ðḅS

Try it online!
Essentially just a translation of jimmy23013's CJam answer, except using n & -n directly as the number of chunks to split into.
        S    The sum of
Ḷ            the range from 0 to the input minus one
 œs          split into sublists of length equal to
   &         the input bitwise AND
    N$       its negation
      ðḅ     with each sublist converted from base-the-link's-argument.

(The ð has nothing to do with mapping: ḅ just vectorizes over its left argument, and ð is there to separate ḅS off as a new dyadic chain which takes the result of ḶœsÇ as its left argument and the argument to the main link as its right argument.)


text:
Piem validator programme
Write a program that defines a function that can check if a string variable called "anything you want or inputted by the user" is or not a piem.
(piem =  a story or poem in which the word lengths represent the digits of π (from Wikipedia))
Some examples:
myfunction("I am clearly wrong") # False
myfunction("How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics") #True (Taken from Wikipedia)
myfunction("Law ' s fine") # True

You should delete any kind of punctuation or newline before processing.
Pure code golf, the shortest wins
End date: evening of 1/10/2014
Various answers

How many digits do we need to handle? More than 10
As a matter of interest, how should 0's in PI be interpreted? Skipped or 10 letter words? As 10 letters words
"a variable called piem" – so the name of the parameter must be piem? No, it hasn't, question text corrected
A fun bonus might be a solution that is itself a piem If your solution is a piem you get *0.5 bonus
For the sake of argument, is _ always punctuation? You can decide if it is punctuation or if it isn't
It's unclear what is meant by "any kind of punctuation" I mean ,.'"?!;;()
So digits should be counted? And Law's fine would be false? Digits should be treated as letters, Law's fine = False; Law ' s fine = True

Comments

The APL solution should be counted in Bytes
If your solution works for 100+ digits of pi you get *0.8 bonus
Because of the great interest the end date is one day more in the future.

How many digits do we need to handle?

So digits should be counted? And Law's fine would be false?

"a variable called piem" – so the name of the parameter must be piem? That renders all current answers incorrect.

Also, should new lines really be removed instead of treated like spaces. Because that means that How\nI\nwant yields false but A\nB\nC yields true.

A fun bonus might be a solution that is itself a piem.

Validating for length (i.e. [3,1,4,1,5,9,2,6,...]) is interesting and a good challenge, but validating a piem, I think, requires that the string actually be a story or a poem.  i.e. something with some sense or memorability to it.  It will be interesting to see how that requirement is handled.  For example, this, despite having appropriate length words, is not a piem in my opinion:  "Bob I door I fence parameter an yellow fence red"

I didn't mean to be overly negative in my previous comment -- I actually think this is a great challenge, particularly if the number of digits of pi is unconstrained.  I just think this isn't really about piems, which require some degree of sense to be memorable.  e.g. also not a piem: "aaa a aaaa a aaaaa aaaaaaaaa aa aaaaaa aaaaa aaa"

As a matter of interest, how should 0's in PI be interpreted? Skipped or 10 letter words?

I don't see any mention of Unicode in the puzzle description...

It's kind of a shame that you don't reply to very important questions, yet you already edited in an end date.

@IngoBürk I now replied, look the question.

APL (39)
{N≡(≢N←≢¨('\w+'⎕S'\0')⍵)↑⍎¨'_. '~⍨99⍕○1}

It uses all the digits the APL interpreter's pi constant provides, to a limit of 99. In my case (Dyalog APL 14 32-bit) that was 16 digits. The 64-bit version likely has more digits. 16 digits is enough for the given examples to work, though.
Strings that have more than that amount of words will fail, even if all the digits it could check were true. (The same is true of other posts, as of this writing.) For example, if there were only 10 digits, the 'How I want a drink' one would fail. This can be fixed, but at the cost of 14 characters:
{(≢¨('\w+'⎕S'\0')⍵){∧/(⌊/≢¨⍺⍵)↑∨⌿⍺∘.=⍵}⍎¨'_. '~⍨99⍕○1}

That version will accept any string where the first N digits are correct.

Your code is the shortes but it is not Unicode... I'll have to think about if you deserve the win or not, the javascript version is just a little bit longer than this... Anyway I upvoted this answer.

@Caridorc a) Do you mean it's not ASCII? Because I'm pretty sure it's Unicode. b) What does the character encoding have to do with anything? APL is as valid a language as any other, it just uses an unconventional set of characters. The more relevant question is whether supporting only a limited amount of digits is valid or not, but you haven't replied to any requests for clarification on the actual challenge.

@marinus The question doesn't specify whether submissions should be scored by characters or bytes, but the default is bytes (as per the tag wiki), so I think your score is closer to 60.

Given the right encoding it's 1 byte per character. APL predates Unicode by decades after all.

@marinus Fair point! Do you know any particular (existing) encoding in which that would actually work?

@MartinBüttner: IBM codepage 907 is one, but there are loads.

JavaScript (169)(140)(137)(135) (63)for 17 digits of pi
In my version Law's fine and Law ' s fine return both true.
Newest Version (63) by Ingo Bürk and hsl
f=s=>!s.split(/\W+/).some((x,i)=>x.length-(Math.PI*1e16+'')[i])

New Version (135) for 17 digits of pi (Thanks to Ingo Bürk):
f=(s)=>{
s=s.split(/[!"#$%&'()*+, \-.\/:;<=>?@[\\\]^_`{|}~]+/);
p=Math.PI*1e16+'';
    r=0;
    for(a=s.length;a--;)r+=s[a].length!=p[a];
    return !r
}

Old version (169) for 32 digits of pi:
f=(s)=>{
s=s.split(/[!"#$%&'()*+, \-.\/:;<=>?@[\\\]^_`{|}~]+/);
p="31415926535897932384626433832795".split('');
    r=1;
    for(a=s.length;a--;)if(s[a].length!=p[a]){r=0};
    return r;
}

You can save 3 bytes with: 1e15*Math.PI+"2384626433832795"

Thanks=) In meantime i changed it using this idea but now only using the first 17 digits.

@IngoBürk Thank you very much, just checking what works.

Sorry, never mind. That doesn't seem to work. :/ The for loop can't be added this way.

But what does work is initializing r=0 and then just looping over r+=s[a].length!=p[a] (you can omit the ; in the end). Then, return !r.

I was just able to improve this, but you are right this willa gain save me 2 bytes I think.

It will probably be shorter to use s.some(…) instead of a for loop, too.

114 bytes: f=(s)=>{p=Math.PI1e16+'';return !s.split(/[!"#$%&'()+, -./:;<=>?@[\]^_`{|}~]+/).some((x,i)=>x.length!=p[i])}

And 103 bytes: f=(s)=>!s.split(/[!"#$%&'()+, -./:;<=>?@[\]^_`{|}~]+/).some((x,i)=>x.length!=(Math.PI1e16+'')[i])

(Alternatively, omit the !, change != to == and use every – same byte count)

I just tried it myself (it is commented now) and your last version, but it does not seem to work as expected? (I was not familiar with the some function: http://jsfiddle.net/dfk8k39L/1/

The backslashes got messed up. Take it from here: http://jsfiddle.net/dfk8k39L/2/

And finally 102 bytes. I don't think I can do any better now (except for the regexp): http://jsfiddle.net/dfk8k39L/3/

Any reason you can't use [^a-zA-Z0-9]+ for the split regex? Also, you can remove the parentheses around s in the function definition.

With @hsl's improvements this now comes down to 73 bytes: http://jsfiddle.net/dfk8k39L/4/

And using character classes, we get 63: http://jsfiddle.net/dfk8k39L/6/

I just add my answer using character classes and 'some'. All these comments were too much too read.

w00t, this is insane=) Thank you!

Ruby, 113 101 79 (98 * 0.8)
require"bigdecimal/math"
x=->p{!(BigMath.PI(999).to_s[2..-1]!~/^#{p.scan(/\w+/).map(&:size)*''}/)}

Explanation

Input is taken as the argument to a lambda. It expects a String.
Pi is calculated up to 999 decimals and turned into a String with the . removed.
Punctuation marks are removed from the poem and it is split into individual words. "Let's" is counted as two words: "Let" and "s".
Use Array#map to convert each word to the size of the word, concatenate them into a String.
Using a Regexp, check if the two created Strings begin with the same characters.

I have applied the bonus for handling 100+ digits. _ is not handled as punctuation in this solution.

Note that you're not treating _ as punctuation.

Well spotted. For the sake of argument, is _ always punctuation? What about sentences such as My nickname on Stack Overflow is britishtea_500.

It was just an observation. The OP isn't exactly specific about the details here.

Fair enough. I'll leave the answer up for now until it's specified in the problem :)

Using bigdecimal you have no limit on PI digits? Nice (+1)

You can specify the number of digits (it's a method, not a constant). I chose a limit of 999, so the program would execute reasonably fast and still be able to deal with bigger poems.

Mathematica, 123 bytes * 0.8 = 98.4
f=#&@@RealDigits[Pi,10,Length[d=StringLength/@StringSplit@StringReplace[#,RegularExpression@"[!-.:-?]
"->""]/. 10->0]]==d&;

Almost the longest submission so far, but:

It works for any number of digits of Pi.
It removes all the required ASCII characters and the line break, without splitting the words in those places.
It handles 0-digits in Pi correctly (as 10-letter words)

if it works for number of digits of Pi you get a 0.8 bonus

Python 3 - 129
Doesn't account for punctuation:
import math
f=lambda p:all(1if len(p.split(' ')[i])!=int(str(math.pi).replace('.','')[i])else 1for i in range(len(p.split(' '))))

Python - 130 127 116 - 17 digits of pi
As in @flawr 's answer, Law ' s fine and Law's fine both return True.
Thanks to @Emil for removing 12 characters from the program.
import re
f=lambda x:all(j==int("31415926535897932"[i])for i,j in enumerate([len(s)for s in re.findall("[\w]+",x)]))

You can save 12 characters by not saving l in a variable and by defining the function using lambda.

Java, 185
boolean f(String...s){s=s[0].replaceAll("\\W","~").replaceAll("~+","~").split("~");for(int i=0;i<s.length;){if(s[i].length()!=(int)(Math.PI*Math.pow(10,i++)%10))return 0>1;}return 1>0;}

python 3, 17 digits of pi, 104
import re;f=lambda s:all(map(int.__eq__, map(int, '31415926535897932'), map(len,re.findall('[\w]+',s))))

You can replace the ; with a newline for readability. Also, a number of spaces can be removed.

T-SQL 488 383
And now for a large T-SQL solution :)
CREATE FUNCTION F(@s VARCHAR(MAX))RETURNS CHAR(6) AS BEGIN DECLARE @ CHAR='T',@p VARCHAR(50)='31415926535897932384626433832795028841971693993751',@i INT=0WHILE @='T'AND @s<>''BEGIN SET @i=PATINDEX('%[^a-z0-9]%',@s)IF @i=0RETURN'#True'IF @i-1<>LEFT(@p,1)RETURN'#False'SET @p=STUFF(@p,1,1,'')SET @s=STUFF(@s,1,@i,'')SET @s=STUFF(@s,1,PATINDEX('%[a-z0-9]%',@s)-1,'')END RETURN'#True'END

This creates an inline table valued function that uses a recursive CTE to detect word boundaries.
Creates a scalar function that chews it's way through the words and PI to 31 decimals (first 0).
It is called in the following way
SELECT dbo.f('SQL I golf, a large procedure is normal. Hefty not terse') --#True

CJam, 40
"
,.'\"?!;:"{-}/S%{,PAV#*iA%=V):V}/]0#)!

It's unclear what is meant by "any kind of punctuation"; this solution removes the ,.'"?!;; characters.

Bash and unix tools, 111
f() { grep ^"$(echo "$@"|grep -Po '[\w]+'|xargs -n1 sh -c 'echo ${#0}'|xargs|tr -d ' ')"<<<31415926535897932;

NodeJS 32 digits 230 Bytes
I can't get it shorter with JS :D
var p = "31415926535897932384626433832795", i = 0;
console.log(process.argv[2].split(/[\s,.]+/).every(function(w) {
    if (parseInt(p.charAt(i)) !== w.length) {
        return false;
    }
    i++;
    return true;
}) ? 'True' : 'False');

remove whitespace.


text:
Build a Primitive Root Diffuser
Introduction
When a room has bare, parallel walls, it can create unpleasant repeating acoustic reflections (echoes).  A diffuser is a device mounted on a wall which creates a blocky surface of many different heights.  This has the effect of breaking up the reflected sound into many smaller reflections (each with a different time delay).  The acoustic quality of the room is thought to be greatly enhanced.
Primitive Root Diffuser
The primitive root diffuser uses a grid of (typically wooden) posts, each with a different height (to obtain a different reflection delay time).  The heights of the posts are chosen according to successive powers of a primitive root G, modulo N (a prime number).
Here are some pictures of a primitive root diffuser.
Task
You must write a program or function which takes a prime number N > 2 as its only input.  It must then select a primitive root of N.  G is a primitive root of N if the successive powers of G modulo N generate all the integers from 1 to N-1.  A more formal definition of primitive roots can be found in the Wikipedia article.
Your code must then place these successive powers into an X-by-Y array (or matrix).  Because we want to hang this on the wall, the diffuser should be a convenient shape - as close to square as possible.  The number of entries in the array will be N-1, so its dimensions X and Y should be chosen such that X*Y = N-1, and X is near but not equal to Y (specifically, X and Y are coprime).  For convenience of display, the horizontal dimension should be greater than the vertical dimension.
The order of placement of successive powers of G (modulo N) should start at one corner of the array, then traverse diagonally through the array, wrapping around in both directions until all array positions are filled.  Then the function should return that array, or print it to stdout, whichever you prefer.
We won't concern ourselves with the measurement units used to actually cut the posts to length; we'll assume the units are appropriate for the range of audio frequencies we want to diffuse, and stick to integers.
There's an online calculator, in case you want to check your work.  However, the site appears to be down currently.
Example
Suppose we choose N = 41.  Our program should select one of the primitive roots of N, which are [6, 7, 11, 12, 13, 15, 17, 19, 22, 24, 26, 28, 29, 30, 34, 35].  Suppose our program selects the smallest primitive root, G = 6.
Our program then chooses the squarest dimensions X,Y for the array such that X*Y = N-1.  The clear choice is X=8 and Y=5.
Then our program populates the array with successive powers of G modulo N (starting with G^0), traversing diagonally.  The program then returns/prints the array:
1   14  32  38  40  27  9   3
18  6   2   28  23  35  39  13
37  26  36  12  4   15  5   29
10  17  33  11  31  24  8   30
16  19  20  34  25  22  21  7

Note how it begins with 6^0 mod 41 = 1, then 6^1 mod 41 = 6, then 6^2 mod 41 = 36, then 6^3 mod 41 = 11, etc.
To clarify, the sequence of powers of 6 modulo 41 is:
[1, 6, 36, 11, 25, 27, 39, 29, 10, 19, 32, 28, 4, 24, 21, 3, 18, 26, 33, 34, 40, 35, 5, 30, 16, 14, 2, 12, 31, 22, 9, 13, 37, 17, 20, 38, 23, 15, 8, 7]

Another Example
N = 31
Assuming the program selects G = 11, X = 6, Y = 5, the output is:
1   26  25  30  5   6
4   11  7   27  20  24
16  13  28  15  18  3
2   21  19  29  10  12
8   22  14  23  9   17

A Third Example
N = 37
Assuming the program selects G = 2, X = 9, Y = 4, the output is:
1   12  33  26  16  7   10  9   34
31  2   24  29  15  32  14  20  18
36  25  4   11  21  30  27  28  3
6   35  13  8   22  5   23  17  19

Scoring
Standard code golf rules - the fewest bytes of code producing correct output wins!

if I choose to write a function, can I return the string or should I print it? are there specific requirements for spacing between numbers?

How do you continue if you hit [0,0] before you cover all tiles? Please provide an example for N=37

@proud haskeller:  No spacing requiremnts, returning or printing are both fine.

@PeterTaylor but for example on 17 the grid is 4x4 which means you loop on the diagonal but never give a number for the rest of the tiles

@phosgene did you mean returning the actual matrix instead of a string of the matrix? is that okay?

@proud haskeller:  Sure, any output format is acceptable.  It can have brackets, commas, tabs, or whatever.

I edited the question to specify that X and Y should be as close as possible, while still being coprime.  That eliminates the problems with a 4x4 array for N=17, or a 6x6 array for N=37,

@phosgene but it opens a new problem where N=17 produces a 1x16 "square" :-(

@JanDvorak:  True, but it's unavoidable for this diagonal traverse method.  Even traversing the array normally, you still run into problems with N=47, for example, with a 23-by-2 array as the best choice.  Some primes are better than others.

Mathematica 158
Spaces not needed:
f@n_ := (m = Mod;
        {p, q} = Sort[{y-x, x, y} /. Solve[x*y==n - 1 && x~GCD~y == 1 < x < y, Integers]][[1, 2 ;;]];
        (g[#~m~p + 1, #~m~q + 1] = m[PrimitiveRoot@n^#, n]) & /@ (Range@n - 1);
         g~ Array~{p, q})

The last one looks like this ...

I'm definitely going to steal these infix tricks!

@phosgene You're welcome:)

Teaching Haskell a thing or two about lazy golfing, I see  :D

@MartinBüttner Yup. Thanks. Also, I'm quite sure the factorization can be done better. I tried the minimization functions with inconsistent results

Haskell, 220 213 207 201 194 182 178
f n=[map(x%)[0..j-1]|x<-[0..i-1]]where j=[x|x<-l,x^2>n,(n-1)&x<1,gcd(n`div`x)x<2]!!0;i=n`div`j;0%0=1;a%b=([x|x<-l,all((>1).(&n).(x^))l]!!0*(a-1)&i%((b-1)&j))&n;l=[1..n-2]
(&)=mod

this is a function which returns a matrix (a list of lists of Int).
it works by calculating the smallest possible g, the closet coprime j and k and defines a recursive function that given the indices of a slot in the grid returns the Integer in it, and maps this function over all slots.
example output:
*Main> mapM_ print $ f 13 -- used for printing the matrix line-by-lie
[1,5,12,8]
[3,2,10,11]
[9,6,4,7]

*Main> mapM_ print $ f 43
[1,21,11,16,35,4,41]
[37,3,20,33,5,19,12]
[36,25,9,17,13,15,14]
[42,22,32,27,8,39,2]
[6,40,23,10,38,24,31]
[7,18,34,26,30,28,29]

*Main> mapM_ print $ f 37
[1,12,33,26,16,7,10,9,34]
[31,2,24,29,15,32,14,20,18]
[36,25,4,11,21,30,27,28,3]
[6,35,13,8,22,5,23,17,19]

It's like hitting a golf ball with a category theory textbook!

Nice use of list comprehension, maybe it's a good idea to add to the Haskell golfing tips if it's not already there.

@TheSpanishInquisition Yes, actually

Python 2: 232 217 212 208 201 198 194 192 187 bytes
N=input()
w=n=G=N-1
Z=range(n)
while sorted(G**x%N-1for x in Z)!=Z:G-=1
while w*w/n|n%w|1-all(w%i|n/w%i for i in Z[2:]):w-=1
n/=w
a=[]
for x in Z:a+=[n*[0]];a[x%w][x%n]=G**x%N
print a[:w]

Now it selects the largest root instead of the smallest, so output is different.
Example:
41
[[1, 27L, 32L, 3L, 40L, 14, 9L, 38L], [18L, 35, 2L, 13L, 23L, 6L, 39, 28L], [37L, 15L, 36, 29L, 4L, 26L, 5L, 12L], [10L, 24L, 33L, 30, 31L, 17L, 8L, 11L], [16L, 22L, 20L, 7L, 25, 19L, 21L, 34L]]

Looks like a close race so far!

a+=[n*[0]]; -> a+=n*[0],;.

MATLAB w/ Symbolic Toolbox - 199 198 bytes
Minified:
function C=F(N),M=N-1;y=1:N;p=y-1;t=@(x)eval(mod(sym(x).^p,N));l=M./y;L=fix(l);k=y(l==L.*gcd(y,L)&y>M^.5);k=k(1);l=M/k;C=eye(l,k);g=y(arrayfun(@(x)sum(t(x)<2)<3,y));C(mod(p,k)*l+mod(p,l)+1)=t(g(1));

Expanded:
function C = primroot( N )

M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( mod( sym(x).^p, N ) );
l = M./y;
L = fix( l );
k = y( l == L.*gcd(y,L) & y > M^.5 );
k = k(1);
l = M/k;
C = eye( l, k );
g = y(arrayfun( @(x) sum( t(x) < 2 ) < 3, y ));
C(mod(p,k)*l+mod(p,l)+1) = t(g(1));

Sample Outputs
primroot(37)

ans =

 1    12    33    26    16     7    10     9    34
31     2    24    29    15    32    14    20    18
36    25     4    11    21    30    27    28     3
 6    35    13     8    22     5    23    17    19

primroot(41)

ans =

 1    14    32    38    40    27     9     3
18     6     2    28    23    35    39    13
37    26    36    12     4    15     5    29
10    17    33    11    31    24     8    30
16    19    20    34    25    22    21     7

primroot(31)

ans =

 1     6     5    30    25    26
16     3    18    15    28    13
 8    17     9    23    14    22
 4    24    20    27     7    11
 2    12    10    29    19    21

primroot(113)

ans =

  1    48    44    78    15    42    95    40   112    65    69    35    98    71    18    73
106     3    31    19     8    45    13    59     7   110    82    94   105    68   100    54
 49    92     9    93    57    24    22    39    64    21   104    20    56    89    91    74
109    34    50    27    53    58    72    66     4    79    63    86    60    55    41    47
 28   101   102    37    81    46    61   103    85    12    11    76    32    67    52    10
 30    84    77    80   111    17    25    70    83    29    36    33     2    96    88    43
 16    90    26     5    14   107    51    75    97    23    87   108    99     6    62    38

A noble effort for MATLAB (even if I do say so myself), the language that requires a1 = b(c); a = a1(d); because it doesn't understand a = b(c)(d). :P
A few notes:

the routine exploits the fact that mod( j^k, N ) for k = 0..N-1 is strictly positive for positive j, and that j is only a primitive root of N if the number 1 appears exactly twice in the sequence
the routine exploits the fact that a number x >= 2 can only equal floor(x)*gcd(floor(x),y) for positive y if floor(x) == x and gcd(floor(x),y) == 1. Also, the fact that x and y are coprime iff gcd(x,y) == 1.

Other than that, I couldn't find any problem-specific optimizations.
MATLAB's mod function is particularly painful since I use it 3 times, and it takes a minimum of 8 characters per invocation, as opposed to 3 (i.e. x%y) for virtually every other programming language in existence. The arrayfun (which in every other language is either map or -> is also painful.
In light of these handicaps, I also present the following solution:
Fantasy MATLAB - far fewer bytes
C = @(N):
M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( sym(x).^p % N );
L = fix( l = M./y );
k = y( l == L.*gcd(y,L) & y > M^.5 )(1);
C = ones( l = M/k, k );
C( p%k*l + p%l + 1 ) = t(y( x -> sum( t(x) < 2 ) < 3 )(1));

I admit I didn't expect to see MATLAB here.  It seems to golf pretty well for this problem!

@phosgene: I needed compact variable-precision arithmetic, reasonable matrix handling, and a gcd or coprime function. This rules out C, C++, C#, Java, Javascript, Perl, and Maple, which are the only other standard languages I've coded in long enough to golf. I'm dabbling in CJam, since it's a golfing language. Personally I don't care for the "golf" aspect of challenges. I greatly prefer other criteria for winning. But easily 80% of the challenges on PPCG are golf-related, and beggars can't be choosers. ;)

It's hard to come up with a good win conditions that don't boil down to letting a program brute force a problem for hours.  If I think of any good problems, I'll be sure to post them.

@phosgene: I know exactly what you mean.

With regards to a1 = b(c); a = a1(d);... what's wrong with a = b(c, d) ?

Errors for N = 2. I am definitely learning something from this function declaration though...

@feersum: It works fine if b is a matrix. If b is a function returning a value, not so much. Regarding the N = 2 case, it's both conceptually invalid (a diffuser with a single post wouldn't be a diffuser) and violates the spec ("X is near but not equal to Y"). The only possible dimensions for N = 2 are X = Y = 1, meaning the spec is impossible to satisfy for N = 2.

True, the spec does say "X not equal to Y" at one point. It seems to be a bit self-contradictory. I was going by the requirement of them being coprime.

I fixed the problem definition to exclude N=2.  It causes nothing but trouble.

APL (dzaima/APL), 84 bytes
{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}

Try it on repl.it!
Uses ⎕IO←0 (0-indexing).
A dfn which takes input as a long integer, and returns a matrix of long ints for the first primitive root of ⍵.
Hosted on repl.it since tio is not updated with the latest version of dzaima/APL. The run button runs all testcases.
Explanation
{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}
∘.*⍨⍳⍵-1 create a power table for 0..n-1
⍵|  modulo that by the input ⍵
↓ convert to list of lists
(⍵∘{...}¨⌿⊢) tacit function, filter lists where:
1=≢⍵~⍨⍳⍺ numbers from 1 to n-1 are present
⊃ take the first one
{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0} and do the following:
Dimension finding function(courtesy of ngn):
{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵ do the following with the length of the first list:
∘.×⍨⍳⍵ multiplication table of 1..length
⍸⍵= coordinates at which product = length
(≠/¨⌿⊢) remove the ones which create squares
a← assign the final coordinates to a
⊃⍋+/↑ index of coordinate with highest sum
a⊃⍨ take that coordinate from a
b← assign that to b
(...)⍴0 create a grid of zeroes of that size
⍵@(...)⊢ assign the first list at the following indices:
⍳≢⍵ 1..length
2⌿¨ each replicated twice
b∘|¨ mod b(vectorizes)
This gives the final diagonally oriented matrix.


text:
Get Out of the Turing Tarpit - EasyFlow
I've created a new language called "EasyFlow." Your task is to simplify writing BrainFlow programs by compiling EasyFlow to BrainFlow. That is, you take an EasyFlow program and output a BrainFlow program which does the same thing. EasyFlow is defined as follows:

The program starts out with a list of variables. A variable is anything that matches [a-zA-Z][a-zA-Z0-9]*. The variables are separated by commas and the list is followed by a semicolon.
The program then has zero or more statements. All statements are followed by a ;. Each statement consists of

A print statement print(<variable>);
An input statement, which copies the next input byte into the variable: input(<variable>);.
An assignment: <variable> = <expression>;. An expression consists of an <integer> from 0 to 255 inclusive (but see bonuses for more).
An increment <variable> += <expression> or decrement <variable> -= <expression>.
Control statements

if(<variable>) { <statement>*; }; An if statement, which has a body of one or more if statements. Notice the semicolon at the end of the if statement.
while(<variable>) { <statement>*; }; A while statement.

Comments are denoted with // and, you must ignore everything for the rest of the line.
Spaces can be put anywhere except between variables (so a b is invalid and not equivalent to ab), between integers, and between inputs and prints. Invalid syntax/statements, however, is undefined behavior.
Input:
Input can be taken from anywhere (file, HTML <textarea> element etc.)
Example input (doubles the char code of the input and outputs it as a character):
// Define variables
inputNumber, total;
// Get input
input(inputNumber);
// Set total to inputNumber * 2
// Reduce inputNumber and add 2 to total until inputNumber is 0
while (inputNumber) {
    inputNumber -= 1;
    total += 2;
};
print(total);

Output:
The output should be a valid BrainFlow program which does the same thing as the input program. However, you can use a shorthand notation <command><number> which indicates <command> repeated <number> times. This can only be applied to + - > < commands. Note that this version of BrainFlow overflows numbers at 256, which is also the length of the tape. You do not have to worry about too many slots being taken up, the program is guaranteed to have less than or equal to 100 bytes as variables. In addition, there won't be anything extreme like a[a[a[a ... repeat 50 times ]]]] = 6.
[ The variable inputNumber is at location 0
    and the variable total is at location 1 ]
, Get input for inputNumber
[
        - Subtract 1
        > Move to location of total
        +2 Add two
        < Move to location of inputNumber
]
>. Print the number

Bonuses:
There are a wide variety of bonuses you can earn. Your final score is your character count multiplied by all the bonuses that you earn. The bonuses are:

0.9: Instead of invalid syntax/statements being undefined behavior, fail to compile, printing the line number of the invalid syntax. This means your program should fail to compile on a b = 5; or c = 3 5; or prin  t(a);. (The error message can read E:<line>
0.9: Allow declarations of arrays as <variable>[<integer]. All arrays must have a fixed length. Allow access from arrays using <variable>[<expression>]. Assigning <variable> = <expression> is an invalid statement if <variable> is an array. In addition LEN(<variable>) should return the (constant) length of <variable>.
0.7: Allow <expression> to also be a <variable>. That is, the following should correctly compile: a = b;, a[a[0]] = c;, b[a[a[b]]] = c; and so on. (Of course, the array part only applies if you took that bonus).

These bonuses are obtainable after getting the previous bonus.
0.7: Allow <expression> to be addition and subtraction. That is, we have <expression> + <expression> or <expression> - <expression>.
0.7: Allow <expression> to include ==, !, &&, || operators
0.6: Allow <expression> to include <, <=, >, >= operators
0.5: Allow multiplication. This must follow the order of operations e.g. <epxression> + <expression> * <expression>.

0.00000000000001: Compile C to BrainFlow. (Please don't actually do this)
Example with a few bonuses:

Input: (Calculates the last one-based index of a given number in the string "141592" or 0 if it doesn't exist).
pi[6], inputNumber, index, finalIndex; // An array with 6 slots and input number
pi[0] = 1;
pi[1] = 4;
pi[2] = 1;
pi[3] = 5;
pi[4] = 9;
pi[5] = 2;
input(inputNumber);
inputNumber -= 48; // Get inputNumber as a digit
index = LEN(pi); // evaluates to index = 6
while (index) {
    index -= 1;
    if (inputNumber == pi[index]) {
        finalIndex = index + 1;
        index = 0; // break the loop
    };
};
finalIndex += 48; // Hack to convert to character if finalIndex < 10
print(finalIndex);

You can find an interpreter for brainflow written in coffeescript here (along with the compiled version of the above program).
This is code golf. The answer with the lowest score wins.
Here is my attempt in ES6 javascript function at a whopping 561 characters if white space and comments are removed and with no bonuses:
// Defines a function called `compile`
compile = a => {
    h = a => {
        for (; a;) {
            // Create a copy of the input string
            var c = a;
            // Replace print statements with "."
            a = a[R](l, (a, d) => {
                e(d);
                b += ".";
                return ""
            })[R](m, (a, d) => { // Replace input statements with ","
                e(d);
                b += ",";
                return ""
            })[R](n, (a, d, c, g) => { // Replace equal to, increment, and decrements
                e(d);
                b += (c || "[-]+") + g;
                return ""
            })[R](p, (a, c, f, g) => { // Replace if and while loops
                e(f);
                b += "[";
                h(g);
                "if" == c ? b += "[>]^" : e(f);
                b += "]";
                return ""
            });
            // If the copy is the same as the input string
            // i.e. no changes were made in replacing, we've reached the end, break
            if (c == a) break
        }
    };
    // A function which moves to the variable location
    e = a => {
        // Go to zeroth position
        b += "[>]^";
        // f[a] is where the variable is located, move there
        b += ">" + f[a]
    };
    var b = "",
        R = "replace";
    // Remove comments and whitespace
    a = a[R](/\/\/.*?\n/g, "")[R](/[\s\n\t]+|/g, "");
    // Regexes
    var l = /^print\((.*?)\);/, // Print statements
        m = /^input\((.*?)\);/, // Input statements
        n = /^([a-zA-Z0-9]+)([\+\-]?)=(\d+);/, // Assignments
        p = // If and while statements
        /(if|while)\((.*?)\)\{(.*?)\};/,
        k = a.split(";")[0].split(","); // Get the variables
    a = a.slice(a.indexOf(";") + 1); // Strip variables from program
    // Assign each variable a unique index
    for (var f = {}, c = 0; c < k.length; ++c) f[k[c]] = c;
    // Compile
    h(a);
    return b // Return
};

I'm sure many people can do better!

I take it that golfing your solution to better than 561 bytes wouldn't count as a valid answer?

@COTO Yeah, it's a valid answer. (But keep in mind, the 561 was obtained if whitespace and comments are stripped from the example). Also, make it significantly (maybe 30-50 chars minimum) less than 561 (don't post an answer with 560)

I kind of want to write a C to easyflow compiler now..

Javascript ES6 - 366 bytes
Minified:
C=a=>(R="replace",e=a=>"[>]^>"+C[a],h=a=>a[R](/(if|while)\((.*?)\)\{(.*?)\};/g,(a,c,f,g)=>e(f)+"["+h(g)+(c[2]?e(f):"[>]^")+"]")[R](/print\((.*?)\);/g,(a,d)=>e(d)+".")[R](/input\((.*?)\);/g,(a,d)=>e(d)+",")[R](/([a-z\d]+)(\W?)=(\d+);/ig,(a,d,c,g)=>e(d)+(c||"[-]+")+g),[,k,a]=/(.*?);(.*)/.exec(a[R](/\/\/.*?\n/g,'')[R](/\s+/g,'')),k.split(",").map((a,b)=>C[a]=b),h(a))

Expanded:
C = a => (
    R = "replace",
    e = a => "[>]^>" + C[a],

    h = a =>
        a[R]( /(if|while)\((.*?)\)\{(.*?)\};/g,
            (a, c, f, g) => e(f) + "[" + h(g) + (c[2] ? e(f) : "[>]^") + "]" )

         [R]( /print\((.*?)\);/g,
            (a, d) => e(d) + "." )

         [R]( /input\((.*?)\);/g,
            (a, d) => e(d) + "," )

         [R]( /([a-z\d]+)(\W?)=(\d+);/ig,
            (a, d, c, g) => e(d) + (c || "[-]+") + g ),

    [,k,a] = /(.*?);(.*)/.exec( a[R]( /\/\/.*?\n/g, '' )[R]( /\s+/g, '' ) ),

    k.split(",").map( (a,b) => C[a] = b ),
    h(a)
)

This is simply a tweaked, refactored, and re-golfed version of the reference implementation in the OP. Most of the saved bytes occur through regex optimizations, elimination of loops, and switching from a push (i.e. b += ...) architecture to an inline architecture.
My apologies for the lack of creativity, but it's all I had time for. Hopefully it will inspire a few more intrepid souls to take the plunge. ;)

authors: ОРИОН НАСЛЕДИЕ


text:
Knight's tour game (7x7)
Your job is to solve this chess-related game.
The setup of the game is a 7x7 tile grid, you start on a random tile and you have to hop on each tile, until you hopped on all 49 tiles.
Top left corner is (0,0)
Rules:

you can hop on each tile once.
the only move allowed in the game is to hop two tiles horizontally and one tiles vertically, or two tiles vertically and one tiles horizontally, like a knight in a chess game.
your input should be a tuple representing the coordinates of the starting tile (stdin, file, what you prefer).
your output a list of tuples, representing the coordinates of each hop. If there's no valid combinations, return an empty list (same as above, any output is ok).

This is code-golf, so shortest code wins!

Is this seriously the only similar question? I thought this website covered the Knight's Journey/Knight's Tour pretty thoroughly. As it is, I have no idea if this is close enough to be a duplicate of the other post.

why won't this be called knight's tour straight away?

Since this is usually called the Knight's Tour, I recommend changing your challenge name to something along those lines (with 7x7). Also, usually people don't have an end date on the challenge. We usually just come by every now and then and see if the shortest answer has changed.

Didn't know that was called knight's tour! i'll change right now thanks!

According to http://mathworld.wolfram.com/KnightGraph.html There are no closed tours for m×m boards with m odd so it's not possible to take a single looped solution and simply start on a different square. That makes this reasonably interesting and not a direct duplicate of the linked question, which leaves the start square to choice. According to http://en.wikipedia.org/wiki/Knight's_tour there are 16557521832 directed tours on a 7x7 board so I imagine at least one starts on every square. I assume we only have to find one valid solution for the given input, not all of them!

Actually, thinking about it, because a knight always alternates between black and white squares, he has to start and finish on squares of the same colour as the corner squares. If the corner squares are black and he starts on a white square, he will run out of white squares (24) before he has visited all the black squares (25). So it's not always possible to complete the tour.

@Quincunx, no, it's not the only similar question. And there's another one which was closed as a dupe.

APL (Dyalog Extended), 39 bytes
7 7{3::0⋄(⍋,(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)¯1⌂kt⍺)⊇,⍳⍺}⊂

Try it online!
A version provided by @Adám.
Dyalog Extended has a shortcut to the dfns library ⌂, and a few convenience functions e.g. monadic = which is equivalent to 0∘=, and dyadic ⊇ for multiple indexing. Unfortunately an inner assignment is buggy, so we use a tacit inner function to reference the value of ¯1⌂kt⍺ twice. Otherwise we'd have a 38 byte solution:
7 7{3::0⋄(⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨=w←¯1⌂kt⍺)⊇,⍳⍺}⊂

How the inner tacit function (⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=) works
This tacit function has 5 terms: `⊢`  `⊃⍨`  `⍵`  `⍳⍨`  `⊃∘⍸¨∘=`
A tacit function is grouped by 3 terms from the right:
  ⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=)
A group of 3 terms is interpreted as follows:
  (f g h)w → (f w) g (h w)     ⍝ f, g, h are functions
  (A g h)w → (A  ) g (h w)     ⍝ A is an array
Then we can interpret the above tacit function as
  (⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=))w
  → (⊢ w) ⊃⍨ (⍵ ⍳⍨ (⊃∘⍸¨∘= w))   ⍝ Expand tacit function
  → w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨∘= w           ⍝ ⊢ is identity function; simplify parens
  → w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨ = w           ⍝ (f∘g)w simply expands to f g w
So the code `(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)w` is equivalent to `w⊃⍨⍵⍳⍨⊃∘⍸¨=w`.

APL (Dyalog Unicode), 53 49 bytes
⎕CY'dfns'
7 7{3::0⋄(,⍳⍺)[⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨0=w←¯1kt⍺]}⊂

Try it online!
Golfed 4 bytes by extracting some terms out of the dfn using a tacit form.

Original submission: APL (Dyalog Unicode), 53 bytes
⎕CY'dfns'
{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]}

Try it online!
Because we've got a language that has a Knight's tour solver built in.
Since ¯1 kt 7 7 tries to find all solutions, it's infeasible to actually run the code as-is. For demonstration purposes, the TIO link uses 3x4 board instead.
How it works
The function dfns.kt finds a (possibly open) Knight's tour, where the right argument is the board's dimensions, and the optional left argument is the number of solutions to find. Giving -1 on the left causes the function to search all possible solutions.
⎕CY'dfns'  ⍝ Import the 'dfns' workspace

{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]}  ⍝ ⍵←starting coordinates
                          w←¯1 kt 7 7        ⍝ Find ALL solutions of 7x7 knight's tour
                   (⊃∘⍸¨0=           )       ⍝ Extract the starting coordinates from each solution
                                      ⍳⊂⍵    ⍝ Find the index of the solution that starts at ⍵
               ,w⊃⍨                          ⍝ Fetch the solution and flatten it
      (,⍳7 7)                                ⍝ Take the flattened list of coordinates on 7x7 board
             [⍋                          ]   ⍝ Sort the coordinates by flattened solution
 3::0⋄                                       ⍝ If there's no solution starting with ⍵,
                                             ⍝ catch the Index Error and return 0 instead

Every black square on 7x7 board can be the starting location of a Knight's tour.
The following isn't directly related to the code above, but nevertheless here is a proof by example.
Starting at (0,0), Ending at (5,1)
0  11 22 45 2  13 24
21 46 1  12 23 44 3
10 27 34 39 36 25 14
47 20 37 26 33 4  43
28 9  40 35 38 15 32
19 48 7  30 17 42 5
8  29 18 41 6  31 16

Starting at (1,3), Ending at (6,4)
20 27 10 33 44 1  12
9  32 21 0  11 34 45
26 19 28 43 40 13 2
31 8  41 22 29 46 35
18 25 30 39 42 3  14
7  38 23 16 5  36 47
24 17 6  37 48 15 4

Starting at (2,2), Ending at (3,3)
30 19 40 3  28 17 38
41 2  29 18 39 4  27
20 31 0  13 10 37 16
1  42 11 48 15 26 5
32 21 14 9  12 47 36
43 8  23 34 45 6  25
22 33 44 7  24 35 46

By swapping heads and tails, reflection, and rotation, all black squares can be the starting point of some Knight's tour.
I found these three tours by splitting the board into four groups that can form a continuous loop:
O O O . O O O  |  . . . O . . .  |  . . . . . . .  |  . . . . . . .
O . O O O . O  |  . O . . . O .  |  . . . . . . .  |  . . . . . . .
O O . . . O O  |  . . . . . . .  |  . . O O O . .  |  . . . . . . .
. O . . . O .  |  O . . . . . O  |  . . O . O . .  |  . . . O . . .
O O . . . O O  |  . . . . . . .  |  . . O O O . .  |  . . . . . . .
O . O O O . O  |  . O . . . O .  |  . . . . . . .  |  . . . . . . .
O O O . O O O  |  . . . O . . .  |  . . . . . . .  |  . . . . . . .

and breaking and gluing the chains whenever needed. It's kind of a heuristic, so it would be usually shorter to hardcode the three boards or just run naive DFS.

39 in Extended

50

Python 3 - 241 chars
This will work most of the time, if you live long enough to see the result...
It works by randomly reordering a list of all coordinates until it gets the right answer. If it takes more than 9*10^99 loops, it assumes that there is no answer. (It will be right the vast majority of the time, since the probability of getting the right order is roughly 1 in 6*10^63).
N.B. Yes, I know that this is not really a valid answer.
import random
l=[(x%7,x//7)for x in range(49)]
s=eval(input())
v=lambda x:all(abs((x[i][0]-x[i+1][0])*(x[i][1]-x[i+1][1]))==2 for i in range(len(x)-1))
t=0
while not all(v(l),l[0]==s,t<9e99):
 random.shuffle(l);t+=1
print(l if t<9e99 else[])

I think you could do l=[(x%7,x//7)for x in range(49)] to save a few chars.

Also you can do x/7 instead of x//7, since x is already an integer, integer division is assumed. Every byte counts :)

@stokastic I think this answer is in python 3, otherwise he wouldn't be using eval(input()). In python 3, x/7 will give floating point values.

@FryAmTheEggman That's correct. I've changed the title now to make it more clear.

Python 3 - 272 263
Since this is a code-golf, this is built to be shorter in code, as opposed to faster in execution. Note that if you want solutions that will run in practical amounts of time, that almost requires some kind of dynamic programming, using a hash in addition to a list, and probably even some kind of heuristic. Otherwise, an exhaustive backtracking search may potentially take a very long time. It would be interesting to see a separate contest for the fastest knight's tour finder for all mxn boards for m0<=m<=M, n0<=n<=N
Anyway, here is the code. It expects an input as a tuple, i.e. (0,0)
p=[eval(input())]
def k():
 if 49==len(p):return 1
 n=[(p[-1][0]+x,p[-1][1]+y) for x in range(-2,3)for y in range(-2,3)if(abs(x)+abs(y)==3)]
 for z in n:
  if(min(z)<0 or max(z)>6 or z in p):continue
  p.append(z)
  if(k()):return 1
  p.remove(z)
if(k()):print(p)

Thanks to Fry for the golfing tips!

You can replace True and False with 1 and 0 (not that you need to replace False...). Also, wherever you have a closing bracket you don't need spaces after it: range(-2,3)for. You can also drop the brackets around if conditions: if 49==len(p):return 1.