text:
Calculating (3 + sqrt(5))^n exactly
Today your goal is to find integers a and b given non-negative integer n such that:

You should write a program or a function that takes parameter n and outputs a and b in a format of your choice.
Standard loopholes apply. Additionally, it's intended that you implement the above problem using basic arithmetic yourself. So you may not use built-in exact algebra functionality, rationals, or functions implementing non-trivial mathematical constructs (for example the Lucas sequence).
Shortest code in bytes wins.

Example input/output:

0 → 1, 0
  1 → 3, 1
  2 → 14, 6
  3 → 72, 32
  4 → 376, 168
  5 → 1968, 880
  6 → 10304, 4608
  7 → 53952, 24128
  8 → 282496, 126336
  9 → 1479168, 661504

Dyalog APL, 18 bytes
((3∘×+5 1×⌽)⍣⎕)1 0

This is a program that takes input through ⎕.
 (         )         Monadic train:
  3∘×                3 times argument
     +               Plus
      5 1×⌽          (5 1) times the reverse
(           ⍣⎕)      Apply that function (input) times
               1 0   starting with (1 0)

The features used here were implemented well before April 2015, making this answer valid.
Try it here. Note that tryapl.org is a limited subset of Dyalog and does not support ⎕.

Octave, 26 bytes
[3 5;1 3]**input('')*[1;0]

Because (a+b*sqrt(5)) * (3+sqrt(5)) = (3a+5b) + (a+3b) * sqrt(5),
multiplying input vector
| 1 |    /* a = 1 */
| 0 |    /* b = 0 */

which stands for 1 = (3+sqrt(5))^0
by matrix
| 3 5 |
| 1 3 |

seems natural. Instead of looping n times, we rather raise the matrix to the power of n and then multiply it by input vector.

You're selling yourself short, [3 5;1 3]**input('')*[1;0] is 26 bytes, not 41.

@(n)[3 5;1 3]^n*[1;0] (function handle) would save you five characters, mut nice idea!

Python 2, 50
a=1;b=0
exec"a,b=3*a+5*b,3*b+a;"*input()
print a,b

Multiplies by 3+sqrt(5) repeatedly by its action on the pair (a,b) representing a+b*sqrt(5). Equivalent to starting with the column vector [1,0] and left-multiplying n times by the matrix [[3,5],[1,3]].

Julia, 22 20 bytes
n->[3 5;1 3]^n*[1;0]

This creates a lambda function which takes a single integer as input and returns a  2-element vector of integers corresponding to the solution [a, b]. To call it, give it a name, e.g. f=n->....
Start by multiplying

We can then translate the right hand side of this equation into a 2-column matrix, where the first corresponds to the coefficient of a and the second to the coefficient of b:

Multiply this matrix by itself n times, then right multiply by the column vector (1, 0), and POOF! Out pops the solution vector.
Examples:
julia> println(f(0))
[1,0]

julia> println(f(5))
[1968,880]

J, 20 bytes
+/@:*(3 5,.1 3&)&1 0

Multiplicate the vector [1 0] with the matrix [[3 5] [1 3]] n times.
2 bytes saved thanks to @algorithmshark.
Usage and test:
   (+/@:*(3 5,.1 3&)&1 0) 5
1968 880

   (+/@:*(3 5,.1 3&)&1 0) every i.6
   1   0
   3   1
  14   6
  72  32
 376 168
1968 880

You can get down to 20 by exploiting tacit adverb parsing: +/ .*(3 5,:1 3&)&1 0.

@algorithmshark Thanks, although why (+/@:*&(3 5,.1 3)&1 0) works and (+/@:*&1 0&(3 5,.1 3)) not? Shouldn't the second one bond correctly and the first one swapped?

Got it, they bond as I expected but the outer & makes the powering/looping so you modify the left side input during powering (opposite to the normal right-side modification).

Pyth, 20 bytes
u,+*3sGyeG+sGyeGQ,1Z

u which is reduce in general, is used here as an apply repeatedly loop. The updating function is G -> ,+*3sGyeG+sGyeG, where G is a 2 tuple.
That function translates to 3*sum(G) + 2*G[1], sum(G) + 2*G[1]. s is sum, y is *2.

I chose @randomra's answer over yours because his/hers was posted 16 minutes earlier, sorry.

APL (22)
{⍵+.×⍨2 2⍴3 5 1}⍣⎕⍨2↑1

Explanation:

{...}⍣⎕⍨2↑1: read a number, and run the following function that many times, using [1,0] as the initial input.

2 2⍴3 5 1: the matrix [[3,5],[1,3]]
⍵+.×⍨: multiply the first number in ⍵ by 3, the second by 5, and sum them, this is the new first number; then multiply the first number in ⍵ by 1, the second by 3, and sum those, that is the new second number.

Awww yiss, APL.

Jelly, 13 bytes
5W×U++Ḥ
2BÇ³¡

Try it online!
How it works
5W×U++Ḥ    Helper link. Argument: [a, b]

5W         Yield [5].
  ×U       Multiply it by the reverse of [a, b]. This yields [5b, a].
    +      Hook; add the argument to the result. This yields [a + 5b, a + b].
     +Ḥ    Fork; add the doubled argument ([2a, 2b]) to the result.
           This yields [3a + 5b, a + 3b].

2BÇ³¡      Main link. Argument: n

2B         Convert 2 to binary, yielding [1, 0].
    ¡      Repeat:
  Ç            Apply the helper link...
   ³           n times.

No, I'm pretty sure Jelly was around a long time before the creation of the internet :P

@Doᴡɴɢᴏᴀᴛ For non-competing answers, I prefer keeping the byte count on the second line. This keeps the answer from rising to the top in leaderboards and userscripts, which seems unfair.

Javascript, 63 61 bytes
I am using a recursive evaluation of the binomial: (x+y)^n = (x+y)(x+y)^{n-1}
New(thanks to @edc65)
F=n=>{for(i=y=0,x=1;i++<n;)[x,y]=[3*x+5*y,x+3*y];return[x,y]}

Old
F=n=>{for(i=y=0,x=1;i<n;i++)[x,y]=[3*x+5*y,x+3*y];return [x,y]}

Might want to consider editing your formula. We don't have MathJax anymore.

I thought it was just introduced a few days ago?

Yeah, but it messed up the stack snippets, so it had to be disabled.

I count 63 as is, and can be shortened to 61 F=n=>{for(i=y=0,x=1;i++<n;)[x,y]=[3*x+5*y,x+3*y];return[x,y]}

n=>[...Array(n)].map(_=>[x,y]=[3*x+5*y,x+3*y],y=0,x=1)[n-1] same length

F=(n,x=1,y=0)=>n?F(n-1,3*x+5*y,x+3*y):[x,y] lot shorter

Mathematica, 31
Nest[{{3,5},{1,3}}.#&,{1,0},#]&

CJam, 21 bytes
0X{_2$3*+@5*@3*+}li*p

Try it online.
How it works
0X       " Stack: [ 0 1 ]                                ";
li{      " Do int(input()) times:                        ";
  _2$    " Stack: [ a b ] -> [ a b b a ]                 ";
  3*+    " Stack: [ a b b a ] -> [ a b (b+3a) ]          ";
  @5*@3* " Stack: [ a b (b+3a) ] -> [ (b+3a) 5a 3b ]     ";
  +      " Stack: [ (b+3a) 5a 3b ] -> [ (b+3a) (5a+3b) ] ";
}*       "                                               ";
p        " Print topmost stack item plus linefeed.       ";
         " Print remaining stack item (implicit).        ";

ised, 25 bytes (20 characters)
({:{2,4}·x±Σx:}$1)∘1

I hoped for better, but there are just too many braces needed in ised to make it competent, the operator precedence is not optimal for golfing.
It expects the input to be in $1 memory slot, so this works:
ised '@1{9};' '({:{2,4}·x±Σx:}$1)∘1'

For n=0, the zero is skipped (outputs 1, instead of 1 0). If that's an issue, replace the final 1 with ~[2].

C, 114 bytes
g(n){int i,a[2]={1,0},b[2];for(i=0;i<n;i++)*b=*a*3+5*a[1],b[1]=*a+3*b[1],*a=*b,a[1]=b[1];printf("%d,%d",*a,a[1]);}

This implements matrix multiplication the boring way. For a more fun (quote: "awesomely horrific") 238 byte solution, look no further!
f(n){int p[2][n+3],i,j,k=0,a[2]={0};for(j=0;j<n+3;j++)p[0][j]=0;*p[1]=0;(*p)[1]=1;for(j=0;j<n;j++,k=!k)for(i=1;i<n+3;i++)p[!k][i]=p[k][i-1]+p[k][i];for(i=1;i<n+2;i++)a[!(i%2)]+=p[k][i]*pow(3,n+1-i)*pow(5,(i-1)/2);printf("%d,%d",*a,a[1]);}

Unraveled:
g(n){
    int i,a[2]={1,0},b[2];
    for(i=0;i<n;i++)
        *b=3**a+5*a[1],b[1]=*a+3*b[1],*a=*b,a[1]=b[1];
    printf("%d,%d",*a,a[1]);
}

This could probably be shortened a bit.
Try a test program online!

This is uses a rather overcomplicated algorithm :P

@orlp I couldn't think of a shorter algorithm for this language. I thought this one would work out, but it kind of got out of hand, haha. Implementing matrix multiplication by hand could very well be shorter.

Upvote because this is awesomely horrific.

82 bytes

k2 - 22 char
Function taking one argument.
_mul[(3 5;1 3)]/[;1 0]

_mul is matrix multiplication so we curry it with the matrix (3 5;1 3) and then hit it with the functional power adverb: f/[n;x] applies f to x, n times. Again we curry it, this time with the starting vector 1 0.
  _mul[2 2#3 5 1]/[;1 0] 5
1968 880
  f:_mul[2 2#3 5 1]/[;1 0]
  f'!8  /each result from 0 to 7 inclusive
(1 0
 3 1
 14 6
 72 32
 376 168
 1968 880
 10304 4608
 53952 24128)

This will not work in Kona, because for some reason f/[n;x] isn't implemented correctly. Only the n f/x syntax works, so the shortest fix is {x _mul[(3 5;1 3)]/1 0} at 23 char.

Wow. This use of currying is so smart I feel like my K answer is stupid. Anyway, I raised the issue you found in Kona on their bug tracker.

FYI, this was recently fixed in Kona.

Seriously, 32 bytes, non-competing
,╗43/12`╜";)@4*≈(6*-"£n.X4ì±0`n

Hex Dump:
2cbb34332f313260bd223b2940342af728362a2d229c6e2e58348df130606e7f

Try It Onlline
Obviously not a contender for shortest, but at least the method is original. (Noting that such a problem necessarily indicates a Lucas sequence, as mentioned in the description, this program generates successive terms of the sequences using the recurrence relation
a_n = 6*a_{n-1} - 4*a_{n-2}.)

Haskell, 41 bytes
(iterate(\(a,b)->(3*a+5*b,a+3*b))(1,0)!!)

Usage example: (iterate(\(a,b)->(3*a+5*b,a+3*b))(1,0)!!) 8 -> (282496,126336).

C/C++ 89 bytes
void g(int n,long&a,long&b){if(n){long j,k;g(n-1,j,k);a=3*j+5*k;b=j+3*k;}else{a=1;b=0;}}

Formatted:
    void g(int n, long&a, long&b) {
if (n) {
    long j, k;
    g(n - 1, j, k);
    a = 3 * j + 5 * k;
    b = j + 3 * k;
} else {
    a = 1;
    b = 0;
}}

Same concept:
void get(int n, long &a, long& b) {
    if (n == 0) {
        a = 1;
        b = 0;
        return;
    }
    long j, k;
    get(n - 1, j, k);
    a = 3 * j + 5 * k;
    b = j + 3 * k;
}

The test bench:
#include <iostream>
using namespace std;
int main() {
    long a, b;
    for (int i = 0; i < 55; i++) {
        g(i, a, b);
        cout << i << "-> " << a << ' ' << b << endl;
    }
    return 0;
}

The output:
0-> 1 0
1-> 3 1
2-> 14 6
3-> 72 32
4-> 376 168
5-> 1968 880
6-> 10304 4608
7-> 53952 24128
8-> 282496 126336
9-> 1479168 661504
10-> 7745024 3463680
11-> 40553472 18136064
12-> 212340736 94961664
13-> 1111830528 497225728
14-> 5821620224 2603507712
15-> 30482399232 13632143360
16-> 159607914496 71378829312
17-> 835717890048 373744402432
18-> 4375875682304 1956951097344
19-> 22912382533632 10246728974336
20-> 119970792472576 53652569456640
21-> 628175224700928 280928500842496
22-> 3289168178315264 1470960727228416
23-> 17222308171087872 7702050360000512
24-> 90177176313266176 40328459251089408
25-> 472173825195245568 211162554066534400
26-> 2472334245918408704 1105661487394848768

Welcome to the site, and nice first answer!

Jelly, 10 bytes
31,53Dæ*³Ḣ

Try it online!
Uses matrix. Computes ([[3,1],[5,3]]**input())[0].

C 71 bytes (60 with pre-initialised variables)
Scope for golfing yet but just to prove that C does not have to be "awesomely horrific".
f(int n,int*a){for(*a=1,a[1]=0;n--;a[1]=*a+3*a[1],*a=(5*a[1]+4**a)/3);}

If the values in a are initialised to {1,0}, we do better.
f(int n,int*a){for(;n--;a[1]=*a+3*a[1],*a=(5*a[1]+4**a)/3);}

This is iteratively using the mappings a->3a+5b, b->a+3b but avoiding a temporary variable by calculating a from the new value of b instead.

Your solution overflows integers for large inputs :)

@orlp - That's C for you.  Granted this solution fails earlier than others because of the interim calculation in brackets but it would only manage a couple of extra steps anyway unless I change the datatype.  Is it worth explicitly changing the question to give the range you expect to support?  Probably too late now though.

There is no range to support, a proper solution should work for any input. In C that means you'll have to implement arbitrary width integers, sorry =/

Suggest a[*a=1]=0 instead of *a=1,a[1]=0

K, 37 bytes
f:{:[x;*(1;0)*_mul/x#,2 2#3 1 5;1 0]}

or
f:{:[x;*(1;0)*_mul/x#,(3 1;5 3);1 0]}

They're both the same thing.

Python 3, 49 bytes
w=5**0.5;a=(3+w)**int(input())//2+1;print(a,a//w)

although on my machine, this only gives the correct answer for inputs in the range 0 <= n <= 18.
This implements the closed form formula
w = 5 ** 0.5
u = 3 + w
v = 3 - w
a = (u ** n + v ** n) / 2
b = (u ** n - v ** n) / (2 * w)

and takes advantage of the fact that the v ** n part is small, and can be computed by rounding rather than direct calculation.

This is not a valid solution (you must support any n), but since you're nowhere near being the shortest I don't see a reason to downvote. It's a cool solution.

Scheme, 97 bytes
(define(r n)(let s([n n][a 1][b 0])(if(= 0 n)(cons a b)(s(- n 1)(+(* a 3)(* b 5))(+ a(* b 3))))))


text:
Connecting letters
You should write a program or function which receives a block of chars represented as a string and outputs or returns a similar string in which the letters adjacent in the alphabet are connected.
A visual example (in the form of input => output):
b     d               b     d
                      |\   /|
                      | \ / |
             =>       |  X  |
                      | / \ |
      e               |/   \e
c     a               c     a

Details

Input will be a string containing spaces, newlines and exactly one of each of the first N lowercase letters. 1 <= N <= 26
The lines of the input will be padded with spaces creating a full rectangular block.
Every pair of letters adjacent in the alphabet will be on the same row, column or diagonal line and should be connected with a straight ascii line using \ / | or -. (The line might have a length of 0.)
The following types of two-line overlaps should be handled:
/ and \ become X
| and - become +
/ and / become /
\ and \ become \
| and | become |
- and - become -
[letter] and [anything] become [letter]

No other kind of two-line overlap will occur.
If more than two lines overlap any pair of them will be guaranteed to be one of the valid overlaps. (e.g. [letter] / | triplet will never occur)
Apart from changing spaces into \ / | - X and + input and output should be identical.
Trailing newline is optional but have to be the same for input and output.
This is code-golf so the shortest entry wins.

Examples
Input:
b     d

     h   gi

      e  f
c     a

Output:
b     d
|\   /|
| \ / |
|  X h+--gi
| / \ |  |
|/   \e--f
c     a

Input:
     dk    j

 b    l

 c   fg

     a    m

   i      h
     e

Output:
     dk----j
    /||   /
 b / |l  /
 |X  | \/
 c \ fg/\
    \|/\ \
     a  \ m
    /|   \
   i-+----h
     e

Input:
   eti  sqjh k  p  u  cfm vb owgzyx rnd la

Output:
   eti--sqjh-k--p--u--cfm-vb-owgzyx-rnd-la

Input:
a

Output:
a

really nice ascii art

What if both a X and + overlap should be in the same spot? Or is that not a case we should account for?

@theonlygusti "If more than two lines overlap any pair of them will be one of the valid overlaps" As e.g. / and - are invalid overlaps X and + (/ \ - and |) can't occur at the same position.

Still confused; why not give us some examples?

@theonlygusti: Basically, it's not a case you should account for

Perl, 219
Some improvements may be still possible.
#!perl -p0
/
/;$x="@-";
sub g{map"(?=$_)(.@_)+[".chr(1+ord).chr(~-ord)."]",a..z}
sub f{for$p(g"{$x}"){s/$p/$&&((_."\177"x~-$x)x y!
!!)/se;$_=lc;s![\0\\]!@_!g}$x++}
f"/";y!\17!/!;f"|";f"\\";y/\17/X/;for$p(g){s/$p/$&=~y! |!-+!r/e}

Try me.

JavaScript (ES6) 246 266 280 285 307
Quite bulky ...
A function with string param and returning the modified string. A trailing newline is optional unless the input is just 1 row (I need a newline to find the row len)
Just to make someone happy
F=b=>b.match(/\w/g).sort().map(l=>(q=b.indexOf(l),~p)?[o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{k=(q-p)/d|0;if(k&&k*d+p==q)for(m='/|\\-'[i];(p+=k>0?d:-d)-q;c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)c=b[p]}):p=q,p=-1,b=[...b])&&b.join('')

More readable
F=b=>
  b.match(/\w/g).sort().map(l=>
    (q=b.indexOf(l),~p)?
    [o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{
      k=(q-p)/d|0;
      if(k&&k*d+p==q)
        for(m='/|\\-'[i];
              (p+=k>0?d:-d)-q;
              c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)
            c=b[p]
    })
    :p=q
  ,p=-1,b=[...b])
  &&b.join('')

Test In Firefox/FireBug console
console.log(F('\
b     d\n\
       \n\
       \n\
       \n\
       \n\
      e\n\
c     a\n'))

console.log(F('\
     dk    j\n\
            \n\
 b    l     \n\
            \n\
 c   fg     \n\
            \n\
     a    m \n\
            \n\
   i      h \n\
     e      \n'))

console.log(F('\
b     d    \n\
           \n\
           \n\
     h   gi\n\
           \n\
      e  f \n\
c     a    \n'))

Output
b     d
|\   /|
| \ / |
|  X  |
| / \ |
|/   \e
c     a

     dk----j
    /||   /
 b / |l  /
 |X  | \/
 c \ fg/\
    \|/\ \
     a  \ m
    /|   \
   i-+----h
     e

b     d
|\   /|
| \ / |
|  X h+--gi
| / \ |  |
|/   \e--f
c     a

I count 341 chars.

@mbomb007 don't count indentation whitespace and newlines

source: Stack Exchange

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

sort: votes


text:
Solving a Jigsaw Puzzle!
I've just bought a new jigsaw puzzle but, as a programmer, I'm too lazy to do it by myself. So I've devised a way to encode the pieces, and now I need a way to solve the puzzle itself.
Challenge
A puzzle piece will have from 2 to 4 connecting corners, defined by a letter; and a color, defined by a number.
  a
B 1 c
  D

a 2 b
  C

3 A
b

The challenge is to build the puzzle from the pieces according to the next rules:

Two pieces may only be adjacent if they have a matching connection in the corner where they are adjacent. If a piece doesn't have a connection in one of the sides, that side is a corner and can't be connected to another piece.

Lowercase letters are considered indents and uppercase letters are considered outdents. An uppercase letter connects with its lowercase pair.

The color of 4-adjacent pieces will differ at most by 1.

Every piece can and has to be used exactly once.

Input
Your program will receive a randomized list of the pieces, separated with newlines, as seen in the examples. The input pieces are in the right direction: you don't need to rotate them (there is a bonus for inputs with rotated pieces, see below).
Output
Your program should output a solution to the puzzle, with columns separated by blank space (space or tab are okay) and rows by newlines. It might not be unique, but only one possible solution is required.
1 2 3 4 3 4 5 4
1 1 2 3 4 4 4 5
2 1 1 2 3 4 5 6
3 2 2 3 4 5 6 7
2 3 3 4 5 6 7 8
3 4 4 5 6 7 8 9
3 4 5 6 7 8 9 10

Scoring
The shortest answer in bytes wins.
Bonus
The generator script provides options to randomize the rotation of the pieces, but since it may become more complex, a 50% bonus is awarded to whoever implements it (that is, your-byte-count * 0.5).
For that case, assume all the tiles in the input will have a randomized rotation, except the first one, which will have the rotation of the original grid (so as to avoid having at least 4 different solutions).
Test Cases
Test cases can be obtained using the following ruby scripts:
https://gist.github.com/rcrmn/2ba23845d65649c82ca8
The first one generates the solution grid. The second one generates the puzzle pieces from it. Note that they have optional arguments, described in each ruby file.
Following is an example. It's here because I made it by hand before writing the generator and I got attached to it:
http://pastebin.com/PA9wZHma
This test case should output:
1 2 3 4
2 3 4 5
3 4 5 6

As usual, common loopholes are not permitted.
Good luck!

So, to clarify: the output is just a grid of the colors? (Despite the fact that multiple pieces have the same color and thus are indistinguishable by this type of output?)

Yes, just a grid of colors

Ruby, 1220
Wow that was something... I didn't think it would take THAT much to make this, but hey, only way to learn was try it. It's clear now why there weren't any answers to the question...
Well, I'm sure this is golfable, but It's been a whole job only to make it. Following is golfed code and then ungolfed with some explanations:
e=[[]]
while(a=gets)
if(a=a.chomp)==""
e.push []
else
e.last.push a.chomp
end
end
e.keep_if{|p|p!=[]}
e.map!{|p|m={}
t=p[0].strip
if t.length==1
m[:t]=t
l=p[1].split" "
b=p[2]
else
m[:t]=nil
l=t.split" "
b=p[1]
end
x=l[0]=~/\d/
m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
m[:b]=b.nil? ? nil:b.strip
m}
w=e.select{|p|p[:t].nil?}.length
h=e.length/w
def c(j,p,l)
x=l[0]
y=l[1]
(x==0&&p[:l].nil?||x!=0&&(j[x-1][y].nil?||j[x-1][y][:r].swapcase==p[:l]&&(j[x-1][y][:v]-p[:v]).abs<2))&&(x==j.length-1&&p[:r].nil?||x!=j.length-1&&(j[x+1][y].nil?||j[x+1][y][:l].swapcase==p[:r]&&(j[x+1][y][:v]-p[:v]).abs<2))&&(y==0&&p[:t].nil?||y!=0&&(j[x][y-1].nil?||j[x][y-1][:b].swapcase==p[:t]&&(j[x][y-1][:v]-p[:v]).abs<2))&&(y==j[0].length-1&&p[:b].nil?||y!=j[0].length-1&&(j[x][y+1].nil?||j[x][y+1][:t].swapcase==p[:b]&&(j[x][y+1][:v]-p[:v]).abs<2))
end
def d(j,q,l)
f=[false,[]]
q.each_index{|i|p=q[i]
if c j,p,l
r=q.dup
r.delete_at i
j2=j.dup
j2[l[0]][l[1]] = p
if r.length==0
f = [true,j2]
break
else
n=l[0]+1
l2=[n%j.length, l[1]+n/j.length]
f = d(j2,r,l2)
break if f[0]
end
end}
f
end
j=[]
w.times{j.push [];h.times{j.last.push nil}}
s=d(j,e,[0,0])
h.times{|y|w.times{|x|print s[1][x][y][:v].to_s+" "}
puts''}

Ungolfed:
pieces=[[]]
while (a=gets) # Read the input and separate by pieces when finding an empty line
  if (a=a.chomp)==""
    pieces.push []
  else
    pieces.last.push a.chomp
  end
end
pieces.keep_if{|p|p!=[]} # Remove possible empty pieces
pieces.map!{|p| # Parse each piece
  m={}
  t=p[0].strip
  if t.length==1
    m[:t]=t
    l=p[1].split" "
    b=p[2]
  else
    m[:t]=nil
    l=t.split" "
    b=p[1]
  end
  x=l[0]=~/\d/
  m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
  m[:b]=b.nil? ? nil:b.strip
  m
}
w=pieces.select{|p|p[:t].nil?}.length
h=pieces.length/w

def fits(j,p,l) # This function determines if a piece fits in an empty spot
  (l[0]==0&&p[:l].nil? || l[0]!=0 && (j[l[0]-1][l[1]].nil? || j[l[0]-1][l[1]][:r].swapcase==p[:l] && (j[l[0]-1][l[1]][:v]-p[:v]).abs<2)) &&
    (l[0]==j.length-1&&p[:r].nil? || l[0]!=j.length-1 && (j[l[0]+1][l[1]].nil? || j[l[0]+1][l[1]][:l].swapcase==p[:r] && (j[l[0]+1][l[1]][:v]-p[:v]).abs<2)) &&
    (l[1]==0&&p[:t].nil? || l[1]!=0 && (j[l[0]][l[1]-1].nil? || j[l[0]][l[1]-1][:b].swapcase==p[:t] && (j[l[0]][l[1]-1][:v]-p[:v]).abs<2)) &&
    (l[1]==j[0].length-1&&p[:b].nil? || l[1]!=j[0].length-1 && (j[l[0]][l[1]+1].nil? || j[l[0]][l[1]+1][:t].swapcase==p[:b] && (j[l[0]][l[1]+1][:v]-p[:v]).abs<2))
end

def rec(j,pl,l) # Recursive function to try every piece at every position it can fit
  found = [false,[]]
  pl.each_index{|i|
    p=pl[i]
    if fits(j,p,l) # Try the piece in the spot
      pl2=pl.dup
      pl2.delete_at i
      j2=j.dup
      j2[l[0]][l[1]] = p
      if pl2.length==0 # If we have spent all the pieces, then we have a complete puzzle
        found = [true,j2]
        break
      else             # Keep recurring until we use up all the pieces
        n=l[0]+1
        l2=[n%j.length, l[1]+n/j.length]
        found = rec(j2,pl2,l2)
        break if found[0]
      end
    end
  }
  found
end

j=[]
w.times { j.push []; h.times { j.last.push nil }}
solved = rec(j, pieces, [0,0])
h.times{|y|
  w.times{|x|
    print solved[1][x][y][:v].to_s + " "
  }
  puts ''
}

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


text:
String to Image
A bit of background:
When I first learned about Brainf*ck, one of the first things I did was to write a Java application that would take in a string and create a, somewhat, optimized program to print said string.
Recently, I've been playing around with Piet, and I have been playing with doing the same thing. I have realized that Piet is a rather interesting language that adds a bit to this challenge.
So, I wanted to put the challenge out to my friends at SE. Let's see what you can do with this language.
The Challenge
Write a program or function that takes in some non-empty string of ASCII characters. Process the string so that you generate a Piet program that will print the string and terminate.
Output is a piet source image in whatever format is best for you. PNG is preferred, but not mandatory.
Piet functionality can be tested here.
The Piet code must generate the output string itself. No input from users is allowed.
Only Piet-Approved colors may be used, as seen below:

As this is a popularity contest, winners will be chosen by votes. Ties will be broken by source code size.
Bonus points will be awarded at my discretion based on the creativity of the output images. These are pictures, after all.

C, (78 + 26 * strlen) codels
This was surprisingly tricky to optimize, mostly because of the possibility of color collisions in neighbouring lines.
The characters are converted to base 12, so each character is a 2-digit number. Every standard line contains the following: pointer (now right for odd lines, left for even lines), duplicate (the number 12, which is first on the stack), push (1st digit), multiply, push (2nd digit), add, outc, push (1 for odd lines, 3 for even lines), duplicate, whitespace, pointer (now down at the end of the line).
To avoid color collisions in neighbouring lines the state after whitespace filling is remembered, and the generation is rolled back to it if a collision happens. The next try starts there with the next color.
Output for "Hello Piet!":

asciipiet2.c
#include "img.h"

#define WIDTH 26
#define OP(op, h, d) int op() { hue += h; dark += d; hue %= 6; dark %= 3; return setp(); }
#define CCMP(c1, c2) (((c1).r == (c2).r) && ((c1).g == (c2).g) && ((c1).b == (c2).b))
#define OPCNT(op) if(op) continue

Color piet[6][2] =
{
    {{0xff, 0xc0, 0xc0}, {0xff, 0x00, 0x00}, {0xc0, 0x00, 0x00}},
    {{0xff, 0xff, 0xc0}, {0xff, 0xff, 0x00}, {0xc0, 0xc0, 0x00}},
    {{0xc0, 0xff, 0xc0}, {0x00, 0xff, 0x00}, {0x00, 0xc0, 0x00}},
    {{0xc0, 0xff, 0xff}, {0x00, 0xff, 0xff}, {0x00, 0xc0, 0xc0}},
    {{0xc0, 0xc0, 0xff}, {0x00, 0x00, 0xff}, {0x00, 0x00, 0xc0}},
    {{0xff, 0xc0, 0xff}, {0xff, 0x00, 0xff}, {0xc0, 0x00, 0xc0}}
};

Color white = {0xff, 0xff, 0xff};

Image img;
int hue, dark, x, y, dx = 1;

void nextline()
{
    x -= dx;
    dx = -dx;
    y += 1;
}

int setp()
{
    if(y > 0 && CCMP(piet[hue][dark], imgGetP(img, x, y - 1)))
    {
        return 1;
    }
    imgSetP(img, x, y, piet[hue][dark]);
    x += dx;
    return 0;
}

void whiteto(int to)
{
    if(dx == 1)
    {
        while(x < to) imgSetP(img, x++, y, white);
    }
    else
    {
        while(x >= WIDTH - to) imgSetP(img, x--, y, white);
    }
}

OP(fill,    0, 0)
OP(pushraw, 0, 1)
OP(pop,     0, 2)
OP(add,     1, 0)
OP(sub,     1, 1)
OP(mul,     1, 2)
OP(divi,    2, 0)
OP(mod,     2, 1)
OP(not,     2, 2)
OP(gt,      3, 0)
OP(pnt,     3, 1)
OP(sw,      3, 2)
OP(dup,     4, 0)
OP(roll,    4, 1)
OP(in,      4, 2)
OP(inc,     5, 0)
OP(out,     5, 1)
OP(outc,    5, 2)

int push(int num);
int pushn(int num)  { int i; for(i = 0; i < num - 1; ++i) { if(fill()) return 1; } return pushraw(); }
int push0()         { return (push(1) || not()); }
int push8()         { return (push(2) || dup() || dup() || mul() || mul()); }
int push9()         { return (push(3) || dup() || mul()); }
int push10()        { return (push(9) || push(1) || add()); }
int push11()        { return (push(9) || push(2) || add()); }
int push(int num)
{
    switch(num)
    {
    case 0:  return push0();
    case 8:  return push8();
    case 9:  return push9();
    case 10: return push10();
    case 11: return push11();
    default: return pushn(num);
    }
}

int main(int argc, char* argv[])
{
    char* str;
    int len, i;

    if(argc != 2)
    {
        printf("Usage: %s \"string to print\"\n", argv[0]);
        return -1;
    }

    str = argv[1];
    len = strlen(str);

    imgCreate(img, WIDTH, len + 3);

    fill(); push(4); push(3); mul(); push(1); dup(); whiteto(WIDTH - 2);
    for(i = 0; i < len; ++i)
    {
        int var, sx = x, sy = y, sdx = dx, fin = 0, off = rand();
        for(var = 0; var < 18 && !fin; var++)
        {
            x = sx; y = sy; dx = sdx;
            hue = ((var + off) % 18) / 3; dark = ((var + off) % 18) % 3;

            OPCNT(fill()); OPCNT(pnt());
            nextline(); pnt(); dup();
            OPCNT(push(str[i] / 12)); OPCNT(mul()); OPCNT(push(str[i] % 12)); OPCNT(add()); OPCNT(outc()); OPCNT(push(2 - dx)); if(i != len - 1) { OPCNT(dup()); }
            whiteto(WIDTH - 2);
            fin = 1;
        }
        if (!fin)
        {
           printf("collision unavoidable\n");
           return -1;
        }
    }
    x -= dx;
    {
        int var, sx = x, sy = y, sdx = dx, fin = 0;
        for(var = 0; var < 18 && !fin; var++)
        {
            x = sx; y = sy; dx = sdx;
            hue = var / 3; dark = var % 3;
            OPCNT(fill()); OPCNT(pnt()); OPCNT(fill());
            fin = 1;
        }
        if (!fin)
        {
            printf("collision unavoidable\n");
            return -1;
        }
    }
    x -= 2 * dx;
    y += 1;
    imgSetP(img, x, y, white);
    x -= dx;
    y += 1;
    hue = 0; dark = 1;
    fill(); fill(); fill();

    imgSave(img, "piet.pnm");

    return 0;
}

img.h
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct
{
   unsigned char r;
   unsigned char g;
   unsigned char b;
} Color;

typedef struct
{
   Color* data;
   int width;
   int height;
} Image;

#define imgCreate(img, w, h)           {\
                                          int length;\
                                          (img).width = (w);\
                                          (img).height = (h);\
                                          length = (img).width * (img).height * sizeof(Color);\
                                          (img).data = malloc(length);\
                                          memset((img).data, 0, length);\
                                       }

#define imgDestroy(img)                {\
                                          free((img).data);\
                                          (img).width = 0;\
                                          (img).height = 0;\
                                       }

#define imgGetP(img, x, y)             ((img).data[(int)(x) + (int)(y) * (img).width])

#define imgSetP(img, x, y, c)          {\
                                          (img).data[(int)(x) + (int)(y) * (img).width] = c;\
                                       }

#define imgLine(img, x, y, xx, yy, c)  {\
                                          int x0 = (x), y0 = (y), x1 = (xx), y1 = (yy);\
                                          int dx =  abs(x1 - x0), sx = x0 < x1 ? 1 : -1;\
                                          int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;\
                                          int err = dx + dy, e2;\
                                          \
                                          for(;;)\
                                          {\
                                             imgSetP((img), x0, y0, c);\
                                             if (x0 == x1 && y0 == y1) break;\
                                             e2 = 2 * err;\
                                             if (e2 >= dy) {err += dy; x0 += sx;}\
                                             if (e2 <= dx) {err += dx; y0 += sy;}\
                                          }\
                                       }

#define imgSave(img, fname)            {\
                                          FILE* f = fopen((fname), "wb");\
                                          fprintf(f, "P6\n%d %d\n255\n", (img).width, (img).height);\
                                          fwrite((img).data, sizeof(Color), (img).width * (img).height, f);\
                                          fclose(f);\
                                       }

#define imgLoad(img, fname)            {\
                                          FILE* f = fopen((fname), "rb");\
                                          char buffer[16];\
                                          int index = 0;\
                                          int field = 0;\
                                          int isP5 = 0;\
                                          unsigned char c = ' ';\
                                          while(field < 4)\
                                          {\
                                             do\
                                             {\
                                                if(c == '#') while(c = fgetc(f), c != '\n');\
                                             } while(c = fgetc(f), isspace(c) || c == '#');\
                                             index = 0;\
                                             do\
                                             {\
                                                buffer[index++] = c;\
                                             } while(c = fgetc(f), !isspace(c) && c != '#' && index < 16);\
                                             buffer[index] = 0;\
                                             switch(field)\
                                             {\
                                                case 0:\
                                                   if (strcmp(buffer, "P5") == 0) isP5 = 1;\
                                                   else if (strcmp(buffer, "P6") == 0) isP5 = 0;\
                                                   else fprintf(stderr, "image format \"%s\" unsupported (not P5 or P6)\n", buffer), exit(1);\
                                                   break;\
                                                case 1:\
                                                   (img).width = atoi(buffer);\
                                                   break;\
                                                case 2:\
                                                   (img).height = atoi(buffer);\
                                                   break;\
                                                case 3:\
                                                   index = atoi(buffer);\
                                                   if (index != 255) fprintf(stderr, "image format unsupported (not 255 values per channel)\n"), exit(1);\
                                                   break;\
                                             }\
                                             field++;\
                                          }\
                                          imgCreate((img), (img).width, (img).height);\
                                          if (isP5)\
                                          {\
                                             int length = (img).width * (img).height;\
                                             for(index = 0; index < length; ++index)\
                                             {\
                                                (img).data[index].r = (img).data[index].g = (img).data[index].b = fgetc(f);\
                                             }\
                                          }\
                                          else\
                                          {\
                                             fread((img).data, sizeof(Color), (img).width * (img).height, f);\
                                          }\
                                          fclose(f);\
                                       }

C, (384 + 256 * strlen) codels, no optimization
No clever hacking in this solution. Every character is represented by a single line with height in pixels = ascii value. Op sequence is then push, outc, push, outc, ...
Output for "Hello Piet!" (and zoom of top part):

asciipiet.c
#include "img.h"

Color piet[6][3] = {
    {{0xff,0xc0,0xc0},{0xff,0x00,0x00},{0xc0,0x00,0x00}},
    {{0xff,0xff,0xc0},{0xff,0xff,0x00},{0xc0,0xc0,0x00}},
    {{0xc0,0xff,0xc0},{0x00,0xff,0x00},{0x00,0xc0,0x00}},
    {{0xc0,0xff,0xff},{0x00,0xff,0xff},{0x00,0xc0,0xc0}},
    {{0xc0,0xc0,0xff},{0x00,0x00,0xff},{0x00,0x00,0xc0}},
    {{0xff,0xc0,0xff},{0xff,0x00,0xff},{0xc0,0x00,0xc0}}
};

Color white = {0xff,0xff,0xff};

int main(int argc, char* argv[])
{
    char* str;
    int len, i, hue, dark;
    Image out;

    if(argc != 2)
    {
        printf("Usage: %s \"string to print\"\n", argv[0]);
        return -1;
    }

    str = argv[1];
    len = strlen(str);

    imgCreate(out, len * 2 + 3, 128);

    hue = 0;
    dark = 1;
    for(i = 0; i < len; i++)
    {
        imgLine(out, i * 2, 0, i * 2, str[i] - 1, piet[hue][dark]);
        dark = (dark + 1) % 3;
        imgSetP(out, i * 2 + 1, 0, piet[hue][dark]);
        dark = (dark + 2) % 3;
        hue = (hue + 5) % 6;
    }
    imgSetP(out, len * 2, 0, piet[hue][dark]);
    imgSetP(out, len * 2 + 1, 0, white);
    imgSetP(out, len * 2 + 2, 0, white);
    imgSetP(out, len * 2 + 2, 1, white);
    imgSetP(out, len * 2 + 2, 2, white);
    imgSetP(out, len * 2 + 2, 3, white);
    imgSetP(out, len * 2 + 1, 3, white);
    imgSetP(out, len * 2, 2, piet[0][4]);
    imgSetP(out, len * 2, 3, piet[0][5]);
    imgSetP(out, len * 2, 4, piet[0][6]);

    imgSave(out, "piet.pnm");

    return 0;
}

img.h
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct
{
   unsigned char r;
   unsigned char g;
   unsigned char b;
} Color;

typedef struct
{
   Color* data;
   int width;
   int height;
} Image;

#define imgCreate(img, w, h)           {\
                                          int length;\
                                          (img).width = (w);\
                                          (img).height = (h);\
                                          length = (img).width * (img).height * sizeof(Color);\
                                          (img).data = malloc(length);\
                                          memset((img).data, 0, length);\
                                       }

#define imgDestroy(img)                {\
                                          free((img).data);\
                                          (img).width = 0;\
                                          (img).height = 0;\
                                       }

#define imgGetP(img, x, y)             ((img).data[(int)(x) + (int)(y) * (img).width])

#define imgSetP(img, x, y, c)          {\
                                          (img).data[(int)(x) + (int)(y) * (img).width] = c;\
                                       }

#define imgLine(img, x, y, xx, yy, c)  {\
                                          int x0 = (x), y0 = (y), x1 = (xx), y1 = (yy);\
                                          int dx =  abs(x1 - x0), sx = x0 < x1 ? 1 : -1;\
                                          int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;\
                                          int err = dx + dy, e2;\
                                          \
                                          for(;;)\
                                          {\
                                             imgSetP((img), x0, y0, c);\
                                             if (x0 == x1 && y0 == y1) break;\
                                             e2 = 2 * err;\
                                             if (e2 >= dy) {err += dy; x0 += sx;}\
                                             if (e2 <= dx) {err += dx; y0 += sy;}\
                                          }\
                                       }

#define imgSave(img, fname)            {\
                                          FILE* f = fopen((fname), "wb");\
                                          fprintf(f, "P6\n%d %d\n255\n", (img).width, (img).height);\
                                          fwrite((img).data, sizeof(Color), (img).width * (img).height, f);\
                                          fclose(f);\
                                       }

#define imgLoad(img, fname)            {\
                                          FILE* f = fopen((fname), "rb");\
                                          char buffer[16];\
                                          int index = 0;\
                                          int field = 0;\
                                          int isP5 = 0;\
                                          unsigned char c = ' ';\
                                          while(field < 4)\
                                          {\
                                             do\
                                             {\
                                                if(c == '#') while(c = fgetc(f), c != '\n');\
                                             } while(c = fgetc(f), isspace(c) || c == '#');\
                                             index = 0;\
                                             do\
                                             {\
                                                buffer[index++] = c;\
                                             } while(c = fgetc(f), !isspace(c) && c != '#' && index < 16);\
                                             buffer[index] = 0;\
                                             switch(field)\
                                             {\
                                                case 0:\
                                                   if (strcmp(buffer, "P5") == 0) isP5 = 1;\
                                                   else if (strcmp(buffer, "P6") == 0) isP5 = 0;\
                                                   else fprintf(stderr, "image format \"%s\" unsupported (not P5 or P6)\n", buffer), exit(1);\
                                                   break;\
                                                case 1:\
                                                   (img).width = atoi(buffer);\
                                                   break;\
                                                case 2:\
                                                   (img).height = atoi(buffer);\
                                                   break;\
                                                case 3:\
                                                   index = atoi(buffer);\
                                                   if (index != 255) fprintf(stderr, "image format unsupported (not 255 values per channel)\n"), exit(1);\
                                                   break;\
                                             }\
                                             field++;\
                                          }\
                                          imgCreate((img), (img).width, (img).height);\
                                          if (isP5)\
                                          {\
                                             int length = (img).width * (img).height;\
                                             for(index = 0; index < length; ++index)\
                                             {\
                                                (img).data[index].r = (img).data[index].g = (img).data[index].b = fgetc(f);\
                                             }\
                                          }\
                                          else\
                                          {\
                                             fread((img).data, sizeof(Color), (img).width * (img).height, f);\
                                          }\
                                          fclose(f);\
                                       }


text:
Optimal Games of Tic Tac Torus
This challenge is about the game Tic Tac Toe, but it's played on a torus.
How to play
To create the necessary game board, you start out with a regular Tic Tac Toe game board. First fold it into a cylinder by joining the left and the right edge. Then fold it into torus by joining the top and the bottom edge. Here's a simple visualization of such a game board with a few moves played (Sick Paint skills!).

The rules of Tic Tac Toe on a torus are the same as regular Tic Tac Toe. Each Player place alternating Xs and Os. The first one with 3 same symbols in a row, a column or a in a diagonal wins.
Since a torus is quite hard to visualize, we simply project the board back onto a paper. Now we can play the game as regular Tic Tac Toe. The only difference is, that you can also win with 3 same symbols in a broken diagonal. For instance Player 1 (X) wins the following board. You can see this easily by changing the view on the torus a little bit.

If your interested, you can play Tic Tac Toe on a Torus at Torus Games. There's a Windows, Mac and Android version.
Optimal Games
In this challenge were interested in optimal games. An optimal game is a game, where both players play an optimal strategy. On a regular Tic Tac Toe board optimal games always end in a draw. Fascinatingly on a torus board always the first player wins. In fact a game on a torus board can never end in a draw (also if the players play not optimal).
The optimal strategy is really easy:

If you can win by placing your symbol, do it.
Otherwise if your opponent has two symbols in one row/column/điagonal, try to block him. Otherwise, do what you want.
Otherwise do what you want.

Every optimal game consists of exactly 7 moves and these moves can be described in the following way:

Player 1 places a X anywhere on the board (9 choices)
Player 2 places an O anywhere on the board (8 choices)
Player 1 places a X anywhere on the board (7 choices)
Player 2's move may be forced (1 choice), if not, he places the O anywhere (6 choices)
Player 1's move is forced (1 choice)
Player 2 is caught in a fork (Player 1 can win in two different ways), so Player 2 has to block Player 1 in one way (2 choices)
Player 1 places the his last move and wins (1 choice)

There are 9*8*1*6*1*2*1 + 9*8*6*1*1*2*1 = 1728 different optimal games on our projected board. Here you can see one typical optimal game:

If we label each cell of the board with the digits 0-8, we can describe this game by the digits  3518207. First a X is places in the cell 3 (middle row, left column), than an O in cell 5 (middle row, right column), than a X in cell 1 (upper row, middle column), ...
Using this digit notation we automatically generated an order. Now we can sort all of the 1728 optimal games and we get the list:
Game 0000: 0123845
Game 0001: 0123854
Game 0002: 0124735
Game 0003: 0124753
Game 0004: 0125634
   ...
Game 0674: 3518207
   ...
Game 1000: 5167423
Game 1001: 5167432
Game 1002: 5168304
   ...
Game 1726: 8765034
Game 1727: 8765043

Challenge
This list is part of your job. You will receive one number k between 0 and 1727 and you have to return the kth game in digit notation of that sorted list.
Write a function or a program, that receives the number k (integer) computes the correspondent game. You can read the input via STDIN, command-line argument, prompt or function argument and print the result (7 digits) in a readable format (e.g. 0123845 or [0, 1, 2, 3, 8, 4, 5]) or return it using an string (human readable format) or an integer (containing all digits in base 10), or in any array/list format.
The challenge type is code-golf. Therefore the shortest code wins.

Why does player 2's first move have to be in the same row or column as player 1's first move? I've played out a few games in my head where player 2's first move is in one of the same diagonals instead and they follow the same optimal game pattern. It seems to me that one of the aspects of the toroidal board is that rows, columns, and diagonals have symmetric effects on the game.

@Runer112 Simplified the optimal strategy a lot. The only rule now is block your opponent if you can, otherwise do what you want.

Just a side comment: actually there are much fewer unique games possible here. Translational symmetry makes the position of the first move irrelevant (because you can always center your view), so divide by 9... and rotation of the board makes for only 2 different second moves (diagonal or adjacent square)... so at most 48 distinct games. If you take into account reflection symmetry, it goes down even further. This torus version is much more boring than the regular one. Golf away.

@orion Actually the fact that torus wraps, does not forbid us to think of '0' as the 'first' rect on the torus board and distinguish all nine fields in general... Yet we agree upon "meridian 0" being at Greenwich, while on the opposite of the Earth we can be one leg in place where it's Thursday, one leg in place it's Wednesday (24h difference in local time!) - and all in spite of the fact that the Earth is round and does not have a "starting point"...

@Rodney Nope, it's a one, not a seven. Try calculating it.

@Jakube Step three says there's 7 choices.  I have no idea what you're telling me to calculate.  Good luck with your puzzle.

@Rodney Yep, there are 7 choices. 6 of them forces the next move of Player 2 => (61) and 1 of them doesn't force the next move so Player 2 has 6 choices => (16). Sorry If I wasn't clear in the question.

JavaScript (ES6), 266 308 317 334 341
A function returning a string.
Edit Found an arithmetic solution for function M (at last!)
F=(n,x=[],M=(a,b,t=-a-b)=>(a-b)%3?a<3&b<3?3+t:a>5&b>5?21+t:12+t:9+t+a%3*3)=>
[for(a of z='012345678')for(b of z)for(c of z)for(d of z)
a-b&&c-a&&c-b&&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c)&&(
f=M(c,e=M(b,d)),g=M(a,e),g<f?[f,g]=[g,f]:0,r=a+b+c+d+e,x.push(r+f+g,r+g+f))]
&&x[n]

Very naive , it can be shortened in many ways. It simply enumerates all the possible legal values and returns what find at place n.
The M function returns the position in between two cells, that is the mandatory move to block an opposite player.
More readable
F=(n,x=[],
  M=(a,b,t=-a-b)=>(a-b)%3?
     a<3&b<3?
       3+t // first row
       :a>5&b>5?
          21+t // last row
          :12+t // middle row and diags
     :9+t+a%3*3 // columns
  )=>
  [for(a of z='012345678') // enumerate the first 4 moves
     for(b of z)
       for(c of z)
         for(d of z)
           a-b&&c-a&&c-b // avoid duplicates
           &&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c) // and check if d must block a-c or it's free
           &&(
             e=M(b,d), // forced to block b-d
             f=M(c,e),g=M(a,e),g<f?[f,g]=[g,f]:0, // f and g could be in the wrong order
             r=a+b+c+d+e, // start building a return string
             x.push(r+f+g,r+g+f) // store all values in x
  )]&&x[n] // return value at requested position

APL (Dyalog Unicode), 73 bytes
⎕⊃z/⍨(∧/{⍵[4⍪3 2⍴5 6 1 3]∊⍨∘{3⊥3|-+/3 3⊤⍵}¨⍥↓⍵[1 3⍪3 2⍴0 4 2]},≠)¨z←,⍳7⍴9

Try it online!
A full program, and takes way too much time and memory to complete for any input. Also, the code includes some 18.0 features that aren't yet available on TIO. The TIO link includes a faster version using only features up to 17.1, so that the output can be checked.
Winning or blocking position
Given two positions, extract their row and column numbers. For each dimension (row/column), if the numbers are the same, so is the result; otherwise, the result is the third number. In both cases, the result coordinates can be found with the following property:
n1  n2  res  -(n1+n2)%3
0   0   0    0
0   1   2    2
0   2   1    1
1   0   2    2
1   1   1    1
1   2   0    0
2   0   1    1
2   1   0    0
2   2   2    2

The resulting code is as simple as the following.
{3⊥3|-+/3 3⊤⍵}  ⍝ ⍵←two positions
        3 3⊤⍵   ⍝ Convert the numbers to base 3, each number → column
      +/        ⍝ Sum of each row
   3|-          ⍝ Negate and modulo 3
 3⊥             ⍝ Convert from base 3 to integer

How the code works
z←,⍳7⍴9      ⍝ Create an array of 7-tuples of 0..8
z/⍨(...)¨z   ⍝ Filter the tuples by the following condition:
  ∧/{...},≠  ⍝ Check that Unique Mask (≠) is all ones AND it is an optimal TTT game:
    ⍵[...] ... ⍵[...]  ⍝ Extract certain indexes of the given tuple as matrices
    ⍥↓                 ⍝ Downrank both sides into four 2-tuples
    ∘{...}¨            ⍝ For each tuple of the right side,
      3⊥3|-+/3 3⊤⍵     ⍝ Compute the cell that completes a line in TTT
    ∊⍨                 ⍝ And check that the right side appears in
                       ⍝ the matching tuple on the left side
⎕⊃  ⍝ Take input n from stdin and pick the nth 7-tuple

-------------------
Left side idxs  ≡ ↓4⍪3 2⍴5 6 1 3 ≡ (4 4)(5 6)(1 3)(5 6)
Right side idxs ≡ ↓1 3⍪3 2⍴0 4 2 ≡ (1 3)(0 4)(2 0)(4 2)

Left  Right  Meaning
1 3   2 0    Turns 1 and 3 (by P1) are blocked by either Turn 2 or 4
4 4   1 3    Turns 2 and 4 (by P2) are blocked by Turn 5
5 6   0 4    Turn 6 blocks one of Turns 1,5 or Turns 3,5, and
             Turn 7 completes the other
5 6   4 2    ↑

APL (Dyalog Extended), 72 bytes
g←{⍵,⍨1⌽@(∊∘⍺)¨⍵}
7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9

Try it online!
Decided to post as a separate answer, because the approach is drastically different.
Inspired from orion's comment, this one generates all optimal games by transforming a single game board in various ways.
The 3x3 toroidal board is very very permissive on its transformations; the three-in-a-rows are preserved through reflection, rotation (e.g. cycling the top row to the bottom), and shear (e.g. cycling elements of each row 0, 1, 2 units to the right respectively). With this information, I could identify four seed boards that have distinct topology (using 0 to 6 to denote the seven moves made in sequence):
P2#4 not forced
0 1 2    0 1 2
3 6 5    3 5 6
x x 4    x x 4

P2#4 forced
0 3 2    0 3 2
1 6 5    1 5 6
x x 4    x x 4

Then I tried various combinations of the transformations to find a short one that generates all 1728 boards. And I noticed that even the seed boards can be generated from one board, by swapping the positions of 1-3 (decides whether the 4th move is forced) and 5-6 (swap a block and a win).
How it works
⍝ Helper function
g←{⍵,⍨1⌽@(∊∘⍺)¨⍵}
1⌽@(∊∘⍺)¨⍵  ⍝ Cycle the positions of ⍺s in each of ⍵
⍵,⍨  ⍝ Prepend the above to ⍵

⍝ Main program
7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9
3 3⍴⊃4 6 8g⊂⍳9  ⍝ Generate the seed board:
0 1 2
3 6 5
8 7 4
5 6g 1 3g  ⍝ Generate four seed boards from the above,
           ⍝ by swapping the numbers 1-3 and 5-6
(⊂⍳3)(...)⍣≡  ⍝ Repeat certain transformations until all are found:
  ⊢∘⌽¨  ⍝ Reverse the order of columns:
a b c   c b a
d e f → f e d
g h i   i h g
  ⊖¨,   ⍝ Join with vertical shear:
a b c   a e i
d e f → d h c
g h i   g b f
  ⌽¨,   ⍝ Join with horizontal shear:
a b c   a b c
d e f → e f d
g h i   i g h
  ∪⊢,   ⍝ Join with original and take unique results

⍋¨,¨  ⍝ Flatten each 3x3 matrix and extract where each number is
∧     ⍝ Ascending sort
⎕⊃    ⍝ Take input n and pick nth result
7↑    ⍝ Take first 7, since the last two are garbage

Octave, 467 369 363 309 297 characters
297:
global t=0*(1:9)m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48 a;
function g(s,p)global a t m;
if nnz(s)<8&&any((t==1)*m>2)a=[a;s];return;end;q=t==3-p;
(r=sort(~q.*(1:9)*m(:,find([3 1]*([q;t==p]*m)==6)')))||(r=find(~t));
for i=r t(i)=p;g([s i+47],3-p);t(i)=0;end;end;g('',1);f=@(n)a(n+1,:);

The only relevant change is that we never check if the current player can win, only check the opponent's possibility to win the next turn.
As the only turn the player 1 can win is turn 7, this is the only place when the algorithm would produce game that is not optimal, but it's very easy to filter such a situation out. We simply verify each game generated if it's won by player 1 - if it was not, the move in turn 7 was incorrect, so we don't add this game to optimal games table.
(Exactly half the games generated by this rule are false ie. in the 7th turn the player 1 always has two possibilities to block player two, but only one will make him win instantly).
Use:
$ octave
octave:1>> source script.m
octave:2>> f(634)
ans = 3270148

The ungolfed code looks like:
 global t=0*(1:9);
 global m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48;
 global allgames;
 allgames=[];

 function r=canbewon(by)
  global t m
  q=[t==by;t==(3-by)]*m;
  g=(find([3 1]*q==6))';
  r=sort((~(t==by).*(1:9)) * m(:,g));
 end

 function games_starting_with(s)
 global allgames t;
 if 7==numel(s) && any((t==1)*m==3) # it's 7th move and first player won
  allgames=[allgames;s];
  return;
 end;
 poss=(find(~t));                  # for now all free slots are possible
 player=1+mod(numel(s),2);
 moves = canbewon(3-player);
 if numel(moves) poss=moves; end;  # ... no, we must block the other player
 for i=poss
  t(i)=player;
  games_starting_with([s char(i+47)]);
  t(i)=0;
 end
end

games_starting_with('');
f=@(n)(allgames(n+1,:));

small hint: you can cut out old versions if they use the same logic since these are stored in the edit history so they are still available

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


text:
Output a Face on a Numbered Cube
Assign the numbers 0 through 7 to the 8 vertices of a cube in any way you want. Exactly one number must be assigned to each vertex.
For example, your vertices might be assigned like this:
  3-----1
 /|    /|
4-----2 |
| |   | |
| 5---|-0
|/    |/
6-----7

Write a program that takes in an integer from 0 to 5. Each of these 6 numbers is associated with exactly one face of your cube in any way you like. When one of these numbers is input, the 4 vertex numbers of the associated face must be printed to stdout in a 2×2 square of digits. The face is to be viewed straight on from outside the cube. All 4 face rotations are valid.
For example, if 0 is associated with the front face of the example cube above, then this would be a valid output for input 0:
42
67

The face may be viewed at any 90° rotation, so these are also valid:
27
46
76
24
64
72
This output (and its rotations) are not valid, as they are viewed from the wrong side of the face:
24
76

The same idea applies to all other faces. e.g. if 1 is associated with the back face, then input 1 might produce output 13[newline]05 (and 31[newline]50 would be invalid).
So the real challenge is choosing your vertex numbers and rotations such that translating the input into its 4 vertex numbers is easy and short.
The shortest code in bytes wins. Tiebreaker is earlier post. (Handy byte counter.)
Notes

You may write a function instead of a program. It should take an integer from 0 to 5 and print or return the 2×2 digit grid string.
Take input from stdin, command line, or function arg. You may assume input is  valid.
The output may optionally have a trailing newline.
Be sure to tell us the vertex and face numbers you chose.

CJam, 23 16 bytes
There's probably an elegant mathematical solution to this problem. But I have no clue how to find one, so super compressed hard coding it is!
I found one! Well, it's not a classically elegant mathematical solution as it uses bitwise operations, but it is entirely formulaic.
li_o1^_p_6|o3+6%

Try it online.
Cube layout
  4-----7          4-----7          3-----2
 /|    /|         /  0  /|         /  3  /|
1-----0 |        1-----0 |        6-----5 |
| |   | |        |     |2|        |     |4|
| 5---|-2        |  1  | 2        |  5  | 7
|/    |/         |     |/         |     |/
6-----3          6-----3          1-----4

Explanation
My old answer already laid out the cube such that each face can be described with its first (top-left) vertex number equal to the face number. But I wanted to be able to calculate more vertex numbers using the face number. At some point, I came up with the idea that got my foot in the door, to calculate the second (top-left) vertex number as the face number XOR 1. And after a while of trial and error, I managed to come up with the layout shown above and the formulas below that allow me to to calculate every vertex number for a face n quite succinctly:

Top-left: n
Top-right: n^1
Bottom-left: (n^1)|6
Bottom-right: ((n^1)+3)%6

For reference, I'll reproduce the output for each face in the desired layout here:
Face:      0     1     2     3     4     5

Vertices:  01    10    23    32    45    54
           74    63    70    65    72    61

So the whole program just comes down to reading the input face number and producing these values in order, albeit with slightly different printing logic for different vertices. Note that, because every vertex after the first starts with a base of n^1, I only need to calculate that once, which compacts the logic even further.

For posterity's sake, and because I think it was still a pretty good approach, here's my old answer.
CJam, 23 bytes
There's probably an elegant mathematical solution to this problem. But I have no clue how to find one, so super compressed hard coding it is!
"pÜ×ñè¨"487b8b3/ri_o=~p

Try it online.
Cube layout
  0-----7          0-----7          3-----6
 /|    /|         /  0  /|         /  3  /|
1-----2 |        1-----2 |        4-----5 |
| |   | |        |     |2|        |     |5|
| 5---|-6        |  1  | 6        |  4  | 7
|/    |/         |     |/         |     |/
4-----3          4-----3          1-----0

Explanation
The basic approach employed is to hard code the vertices for each face in as little space as possible. Similarly to Optimizer's base conversion solution, this treats the vertex list as an octal number packed as ASCII character data. But that's about where the similarities end to make way for further optimizations!
Here are the three key optimizations I made to the "naive" solution:

Lay out the cube such that each face can be described with its face number as the first vertex number. Looking at my cube layout as presented above, one can see that the top-left vertex number of each face is equal to the face number. This allows me to encode six fewer vertices at the cost of having to print the input back, which turns out to save a byte.
Pack the vertex data into a string for which each "character" has a maximum larger than 256. As this maximum increases past 256, the length of the string slowly decreases, but it becomes increasingly likely that any one "character" exceeds 256 and is thus no longer part of the 1-byte ASCII character set. So I wrote a program that tries encoding the vertex data in every base from 256 to 1000, with which I found about 10 bases that save one byte of character data compared to base 256. I chose 487, as that also has the nice property that the resulting string consists entirely of printable ASCII.
Mixed with the first optimization, produce the output asymetrically. The usual approach in CJam would be to format the vertex data as a 2-element list of 2-element lists, insert a newline in the middle, and let the output be implicitly printed. But I instead print the first vertex (equal to the input face number) with an operator that doesn't add a newline, retrieve the 3-element list of the other vertices, grab the next vertex and print it with an operator that does add a newline, and let the other two vertices be implicitly printed. This saves a byte.

I tried permutations as an elegant mathematical approach and it's more verbose than hard-coding without your optimisations.

Your latest answer is brilliant. I think you should have posted it as a separate answer as it's a completely different approach and worthy of another upvote. Basically you have the same cube as my C answer but with the first three even corners shifted one place. I can't believe I missed 6+n%2 --> 6|n (i've already incorporated that into my Ruby answer.) Note that by performing the transform n --> n^1 on the faces you could simplify your formulas, though I'm guessing that as you discard n and carry on with n^1 it won't help your score.

@steveverrill Thanks for the praise! I asked in chat if I should post this as an entirely new answer, but there wasn't a consensus so I didn't. I was definitely pleased with myself when I realized that carefully ordering the n and n^1 pairs around the cube would allow me to calculate another vertex with just |6. And I didn't see that n --> n^1 transform, which definitely makes sense. But you correctly surmised that it wouldn't actually affect my score, so I'll probably just leave it as-is.

I've gone ahead and incorporated your XOR idea into my Ruby answer. It gives a saving of 10 (in addition to the 2 for 6+n%2 --> 6|n) I hope you don't mind. I did use the n --> n^1 transform on the faces, so my latest revision gives the same outputs as yours, but with different inputs. BTW, I don't think bit operations are inelegant, it all depends how you use them!

1 char shorter in GolfScript: ~.1^..n@6|@3+6%

@PeterTaylor It's been so long since I've used GolfScript that I forgot about the wonderful feature that input is automatically put on the stack. Good catch. I think a couple of people have asked aditsu to modify CJam to implicitly read the input when an attempt is made to read from the empty stack. Unfortunately, nothing has come of this yet.

C,69
f(c){int d=c++%2*2-1;printf("%d%d\n%d%d",(c-d)%6,c%6,c%2+6,(c+d)%6);}

Ungolfed in test program
f(c){
 int d=c++%2*2-1;
 printf("%d%d\n%d%d",(c-d)%6,c%6,c%2+6,(c+d)%6);
}

int n;
main(){
  scanf("%d",&n);
  f(n);
}

Explanation
My cube numbering, when unfolded, looks like this:
0---7
|   |
| 0 |
|   |
1---2---7
|   |   |
| 1 | 2 |
|   |   |
6---3---4---7
    |   |   |
    | 3 | 4 |
    |   |   |
    6---5---0
        |   |
        | 5 |
        |   |
        6---1

The top left corner has the same number as the face.
The bottom right corner has number (n+2)%6
For odd n the top right corner is (n+1)%6 and the bottom left is 6
For even n the top right corner is 7 and the bottom left is (n+1)%6
The program displays the odd numbers as shown and the even numbers rotated 180 degrees. This means that the top right corner is always (n+1)%6 and the bottom left is always (n+1)%2+6. Inverting n and n+2 is easier (it is done by setting c=n+1 and using d to add or subtract 1 or -1 as necessary.)
Output
$ ./a
0
21
70

$ ./a
1
12
63

$ ./a
2
43
72

$ ./a
3
34
65

$ ./a
4
05
74

$ ./a
5
50
61

+1 This is the kind of elegant mathematical solution I was imagining. Unfortunately, it's implemented in C...

@Runer112 Thanks. Unfortunately, C is the language I know best. I'm learning Ruby but I'm still a beginner. Ruby should be able to smash this score but probably not compete with Cjam. Maybe I will post in Ruby later, or just find some minor improvements to my C answer (for example by changing c%6 to c%=6 and rotating the face so it comes first, it should be possible to eliminate some modulus calculations.)  Another thing to experiment with is shifting the face labelling by one place, so I get n-1,n,n+1 instead of n,n+1,n+2.

@steveverrill you are already declaring n global, so you could save a few bytes by declaring it higher, change the signature to f()?  Or are we only looking at the f function here?

@dwcanillas "You may write a function instead of a program" so I'm only counting the function. In any case, this was just a proof of concept in the language I'm most familiar with. I'm more interested in shortening my Ruby answer, which from the start was already much shorter than this.

Element, 18
_4:2%6+``2+6%`-5+`

Unlike many more advanced golfing languages, Element does not have a compression operator, so the brevity of the solution is tied rather closely to the exact numbering scheme used.  After some experimentation, I have created a new numbering scheme which allows the vertices to be computed using only simple arithmetic operations.
  1-----0          1-----0          2-----5
 /|    /|         /  4  /|         /  3  /|
4-----6 |        4-----6 |        3-----7 |
| |   | |        |     |0|        |     |5|
| 7---|-5        |  2  | 5        |  1  | 0
|/    |/         |     |/         |     |/
3-----2          3-----2          4-----1

The top-left corner is 6 if even and 7 if odd.  The top-right corner is the face number itself.  The bottom-left is the face number, plus 2, mod 6.  The bottom-right is 5 minus the face number.
Here is an explanation of the code.
_4:2%6+``2+6%`-5+`
_4:                    take input and make several copies of it
   2%6+`               take face #, mod 2, add 6, and output
        `              output input, which already has the newline attached
         2+6%`         take face #, add 2, mod 6, and output
              -5+`     negate face #, add 5, and output

Here are the outputs for each of the faces:
0
60
25

1
71
34

2
62
43

3
73
52

4
64
01

5
75
10

+1: Although I find your code indecipherable, it's nice to see how this scores in a golfing language. Looks like you're currently in joint 3rd place, behind 2 CJam answers: Peter Taylor and Runer 112.

Now it's in a solid second place, but I don't foresee it beating CJam.

Octave, 108 100 68 50 bytes
Of course ther is a way of doing it way more elegant than my previous approaches, plain hardcoding. I am amazed how Octave is way more suitable for codegolf than Matlab=)
f=@(n)['040201375767';'261345154623'](:,2*n+(1:2))

Layout:
(Sorry, I forgot to add this.)
Cube layout
  1-----5          1-----5          6-----7
 /|    /|         /  2  /|         /  5  /|
0-----4 |        0-----4 |        2-----3 |
| |   | |        |     |4|        |     |3|
| 3---|-7        |  0  | 7        |  1  | 5
|/    |/         |     |/         |     |/
2-----6          2-----6          0-----1

Old Versions:
f=@(n)[0 4 0 2 0 1 3 7 5 7 6 7;2 6 1 3 4 5 1 5 4 6 2 3](:,2*n+(1:2))

Even older Versions:
This is really gonna make a 2x2x2 array and then choosing a 'slice'. We do a 3d matrix permutation and each time choose the top or bottom slice. (This one does not work in matlab because of the indexing of an expression rather than a matrix)
I am sure there would be more direct ways of doing it that would be shorter.
f=@(n)squeeze(permute(reshape(0:7,2,2,2),circshift((1:3)',n))(n=fix(n/3)+1,circshift((1:2)',n-1),:))

f=@(n)squeeze(permute(reshape(0:7,2,2,2),circshift((1:3)',n))(floor(n/3)+1,circshift((1:2)',floor(n/3)),:))

CJam, 31 28 (or 26) bytes
8,2/W%_1m<]z[D75K46]2/+ri=N*

which can also be compressed using base conversion into a 26 bytes version.
Assumes the cube to be like:
  7-----1
 /|    /|
5-----3 |
| |   | |
| 6---|-0
|/    |/
4-----2

with faces like
  7-----1      .-----.      .-----.      .-----.
 /  4  /|     /  4  /|     /  4  /|     /  0  /|
5-----3 |    .-----. |    .-----. |    .-----. |
|     |2|    |     |1|    |     |0|    |     |5|
|  1  | 0    |  0  | .    |  3  | .    |  3  | .
|     |/     |     |/     |     |/     |     |/
4-----2      .-----.      .-----.      .-----.

Try it online here

JavaScript (ES6), 53 62
Edit Save 8 bytes using template strings, thx @NinjaBearMonkey. Beware, the newlines inside quotes are significant and cannot be collapsed.
Can't be clever in Javascript, it's too verbose.
f=n=>`01
23
45
67
01
31
5702
64`.substr(n-4?n*3:20,5)

Output for(i=0;i<6;i++)console.log(f(i),i)

01
  23
  0
23
  45
  1
45
  67
  2
67
  01
  3
02
  64
  4
31
  57
  5

See the snippet to veify the number associations (that was fun)

function P3D(x,y,z) {
    this.x = x;this.y = y;this.z = z;
    this.rotateX = angle => {
        var rad = angle * Math.PI / 180,
        cosa = Math.cos(rad),sina = Math.sin(rad),
        y = this.y * cosa - this.z * sina,
        z = this.y * sina + this.z * cosa
        return new P3D(this.x, y, z)
    }
    this.rotateY = angle => {
        var rad = angle * Math.PI / 180,
        cosa = Math.cos(rad), sina = Math.sin(rad),
        z = this.z * cosa - this.x * sina,
        x = this.z * sina + this.x * cosa
        return new P3D(x,this.y, z)
    }
    this.rotateZ = angle => {
        var rad = angle * Math.PI / 180,
        cosa = Math.cos(rad), sina = Math.sin(rad),
        x = this.x * cosa - this.y * sina,
        y = this.x * sina + this.y * cosa
        return new P3D(x, y, this.z)
    }
    this.project = (viewWidth, viewHeight, fov, viewDistance) => {
        var factor = fov / (viewDistance + this.z),
        x = this.x * factor + viewWidth / 2,
        y = this.y * factor + viewHeight / 2
        return new P3D(x, y, this.z)
    }
}

var vx = [
    new P3D(-1,1,-1),
    new P3D(1,1,-1),
    new P3D(-1,-1,-1),
    new P3D(1,-1,-1),
    new P3D(-1,-1,1),
    new P3D(1,-1,1),
    new P3D(-1,1,1),
    new P3D(1,1,1),
];
// Define the vx that compose each of the 6 faces. These numbers are
// indices to the vertex list defined above.

var faces = [[0,1,3,2],[2,3,5,4],[4,5,7,6],[6,7,1,0],[0,2,4,6],[1,3,5,7]]

faces.map((f,i)=>{
    var mx=vx[f[0]].x+vx[f[1]].x+vx[f[2]].x+vx[f[3]].x,
    my=vx[f[0]].y+vx[f[1]].y+vx[f[2]].y+vx[f[3]].y,
    mz=vx[f[0]].z+vx[f[1]].z+vx[f[2]].z+vx[f[3]].z
    vx[i+10]=new P3D(mx/4, my/4, mz/4)
    f[4]=i
    f[5]=i+10
})

var angle = 0;

var ctx = CV.getContext("2d");

setInterval(loop,33)

function loop() {
    ctx.fillStyle = "#fff"
    ctx.fillRect(0,0,400,200);
    ctx.font = "20px Arial"
    angle += 2

    var t = vx.map(v=>
        v
        .rotateX(angle).rotateY(-angle).rotateZ(-angle)
        .project(400,200,128,3)
    )

    ctx.strokeStyle = "#f00"
    t.forEach((v,i)=>i<8?ctx.strokeText(i,v.x,v.y):0)

    ctx.strokeStyle = "#428"
    ctx.beginPath()
    faces.forEach(f=>(
        ctx.moveTo(t[f[0]].x,t[f[0]].y),
        ctx.lineTo(t[f[1]].x,t[f[1]].y),
        ctx.lineTo(t[f[2]].x,t[f[2]].y),
        ctx.lineTo(t[f[3]].x,t[f[3]].y),
        ctx.lineTo(t[f[0]].x,t[f[0]].y),
        ctx.strokeText(f[4],t[f[5]].x,t[f[5]].y)
    ))
    ctx.closePath(),
    ctx.stroke()
}
<canvas id=CV width=400 height=200></canvas>

If you use ES6 template strings, you can use actial newline characters instead of \n, which should save 8 bytes.

You have to use tick marks ` instead of quote marks for template strings.

Right, that's how I tested it in fact.

Ruby Rev 1,  40 36
->(c){print(c^1,c,"\n",6|c,(c+3)%6)}
Thanks to @rcrmn for suggesting using a lambda to save 4 bytes. I wasn't sure about leaving it anonymous but it seems to have been discussed on meta here and decided this was OK.
Here it is as a 40-byte function, for comparison with my Rev 0 Ruby answer, also below (Original C answer is in a separate post.)
def f(c)print(c^1,c,"\n",6|c,(c+3)%6)end

Further inspiration from Runer112: This relies on a modification of the numbering scheme used in his latest (16 byte!) answer. A direct port of PhiNotPi's scheme would give the same score.
By shifting the numbering from Rev 0 round one step, and taking everything XOR 1, we get the following cube:
4---7
|   |
| 1 |
|   |
1---0---7
|   |   |
| 0 | 3 |
|   |   |
6---3---2---7
    |   |   |
    | 2 | 5 |
    |   |   |
    6---5---4
        |   |
        | 4 |
        |   |
        6---1

Output
0
10
63

1
01
74

2
32
65

3
23
70

4
54
61

5
45
72

Ruby Rev 0, 56 52 50
Saved 4 bytes by removing unnecesary ()%6from c-d and another 2 (inspired by runer112) by 6+c%2 --> 6|c .
Score is for the function, which is just the first line. I'm new to Ruby and I'm surprised I can't find a shorter way than 12 characters (11 plus newline) to get a user input number into n. As a result, doing a function instead of a program saves 1 byte.
def f(c)d=c%2*2-1;print((c+d)%6,c,"\n",c|6,c-d)end

n=gets.to_i
f(n)

This is a port of my C answer. In C, the % operator returns a negative value with a negative number. In Ruby it always returns a positive value, so there is no need to add 1 to c. As a result, it is advantageous to shift the numbering of the faces by 1 as below:
0---7
|   |
| 1 |
|   |
1---2---7
|   |   |
| 2 | 3 |
|   |   |
6---3---4---7
    |   |   |
    | 4 | 5 |
    |   |   |
    6---5---0
        |   |
        | 0 |
        |   |
        6---1

With the new face numbering, the program prints the evens as shown above and the odds rotated through 180 degrees:
1
21
70

2
12
63

3
43
72

4
34
65

5
05
74

0
50
61

I believe you can shorten the function by using lambdas: ->(x){...code...} which leaves your function definition 4 characters shorter. You then have to assign it to a variable to use it, and call it with #call

@rcrmn thanks, you're right, f=->(c){print(c^1,c,"\n",6|c,(c+3)%6)} does run and is 2 characters shorter (4 characters shorter if I omit the f=). Not sure if its fair to omit f= but the question doesn't say the function can't be anonymous. What I find odd is that this syntax is totally different from the syntax shown to beginners, that has the passed parameter inside the braces: f=lambda{|c|print(c^1,c,"\n",6|c,(c+3)%6)}

This is what's called a lambda literal. And indeed I always find it difficult to find a reference when I need to remember the syntax...

CJam (25 bytes)
"ñRXµ  roM~"(ib65b2/q~=N*

This contains a non-printable character and a tab (which will be mangled by the StackExchange software), so in xxd format:
0000000: 22f1 5258 1fb5 0972 6f4d 7e22 2869 6236  ".RX...roM~"(ib6
0000010: 3562 322f 717e 3d4e 2a                   5b2/q~=N*

Online demo
Cube:
  1-----0        Faces:
 /|    /|        10 46
4-----6 |        14 37
| |   | |        20 31
| 3---|-2        23 57
|/    |/         56 20
7-----5          57 64

This is pure hard-coding, with the cube vertices selected to maximise base compressibility. I decode to 2-digit numbers, so none of them can begin with 0. I don't want any to begin with 7 either, since that pushes the second base too high. Therefore 0 and 7 must be on a long diagonal. I want a 10 edge to go first to reduce the value I'm encoding. Other than that, there's a fair amount of flexibility without changing the byte count.
I'm slightly disappointed that having popped the first character from the magic string, it's necessary to cast it to an int before using it as a base for base conversion. Hopefully future versions of CJam will save that byte, although it will be too late to exploit that here.

Pyth, 30
Thanks @Jakube for 2 bytes.
Jc2jkfx>Q2!.&T^2%Q3U8jb?_J%Q2J

Try it here.
Golfing advice from pyth experts will be graciously accepted.  In particular I think the output section might have some improvements.
Port of the following python:...
Python, 109
Q=input()
s=''.join(map(str,filter(lambda v:(Q<3)^(v&(1<<Q%3)>0),range(8))))
print s[1-Q%2::2],'\n',s[Q%2::2]

...which is a port of
Pure Bash, 130
For the purposes of explanation:
for v in {0..7};{
if(($1/3));then((v&(1<<$1%3)))&&a+=$v
else((v&(1<<$1%3)))||a+=$v
fi
}
i=$[$1%2*2]
echo "${a:i:2+i}
${a:2-i:4-i}"

The cube vertices are numbered thus:
  4-----5
 /|    /|
0-----1 |
| |   | |
| 6---|-7
|/    |/
2-----3

And the faces are numbered thus:
Face  Vertices  Swap
   0  0,2,4,6
   1  0,1,4,5   x
   2  0,1,2,3
   3  1,3,5,7   x
   4  2,3,6,7
   5  4,5,6,7   x

The Swap column indicates the order of the vertices should be switched in the output.
The algorithm starts out with all vertices {0..7}.  Vertices are eliminated according to bits set in the vertex numbers:

For faces 0,1 and 2, vertices with bits 1,2 or 3 cleared respectively are kept
For faces 3,4 and 5, vertices with bits 1,2 or 3 set respectively are kept

The "kept" vertices are appended to a string.  The string is output chars 0,1 then 2,3 or vice versa, depending on whether the swap flag (face number mod 2) is set.

J - 26 bytes
Function taking face number as argument and returning the grid of digits.
0{.@":"0@{0&(|:|.)&(i.3#2)

We are using the following cube:
  4-----5    Face numbers:
 /|    /|     0 - front
0-----1 |     1 - top
| |   | |     2 - left
| 6---|-7     3 - back
|/    |/      4 - bottom
2-----3       5 - right

Example (try it yourself at tryj.tk):
   0{.@":"0@{0&(|:|.)&(i.3#2) 3         NB. inline
76
54
   f =: 0{.@":"0@{0&(|:|.)&(i.3#2)      NB. named
   f each 0 1 2 3 4 5                   NB. all results
+--+--+--+--+--+--+
|01|40|64|76|37|13|
|23|51|20|54|26|57|
+--+--+--+--+--+--+

The bread and butter is 0&(|:|.). This is a verb that reverses and rotates the cube in such as way as to visit every face when iteratively applied, which is what we do using the input argument. The vertices of the cube are generated by i.3#2, so we use that as the starting point, and take the front face 0...{ when we're done.
Printing the digits as a string costs 8 chars: {.@":"0@ If we were allowed to simply return an array, that's a saving of 8 whole characters. [commences fist-shaking and indiscernible griping]

Results for 1, 4 and 5 appear to be reversed

><> (Fish), 38 bytes
'/ =/2= 28"H5'a@i-!
noan~\;
~>:?!^1-@~

Every output is stored as two 2-digit rows. The rows are stored as charcodes in the string '/ =/2= 28"H' (except the row 10 which is appended after the string as a). The first character (/ = 47) is used to redirect the program flow on the second interaction.
The top 2*(53-n) elements are discarded (where n is the charcode of the input number) and the next two codes are printed with a newline between.
Layout:
  3-----2
 /|    /|
4-----7 |
| |   | |
| 5---|-0
|/    |/
6-----1      0 1 2 3 4 5 sides are top front bottom back left right respectively.


text:
Tips for golfing in The Shakespeare Programming Language
What general tips do you have for golfing in The Shakespeare Programming Language? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to SPL (e.g. "remove comments" is not an answer).
Please post one tip per answer.

I'm not certain that you can golf SPL. SPL is so verbose that I almost feel like this question needs the code trolling tag. :P

You just can't golf SPL. At least, to my feeble knowledge of Shakesperian lore...

@RodolfoDias: Feeble? I think you're the resident Shakespeare scholar on PPCG.

@AlexA. Which may not be a good thing: it just means I'm demented enough to try and understand SPL :-)

@AlexA. Sp can do it...

This is not a golfing tip, but a note. On Listen tothy! command (aka int_input) it's undefined behavior if there are nothing left in the input, so you can't reliably determine EOF with integer input.

(Well... since this is my adopted language 1, I feel like I'm obliged to add something here)
Use short variable names
Yeah, yeah, yeah, that's pretty standard to code-golf, you just use one-letter-length variable names, no news here. Or is there? Because the chaps that created SPL were wacky enough not to allow any name for their language's variables: they must come from Shakesperian plays which, in terms of character length, is a pain in the royal tush - but, if you're coding in SPL, you already know that. So, my advice would be to use characters with short names, like Ajax, Ford, Page or Puck, instead of The Archbishop of Canterbury, per instance.
That's all I got, I'm afraid.

1- since my Java skills are equivalent of those of a newborn.

Variable name list.

Any Roman numeral is a valid scene number
That means, that instead of:
Scene I
Scene II
Scene III
Scene IV
Scene V

You can do:
Scene L
Scene I
Scene C
Scene X
Scene V

is D a valid Roman numeral? IIRC, it's 500 (but I'm not sure if it's valid in SPL)

@Giuseppe I don't understand why you don't just check that, but the official SPL interpreter supports M, C, D, X, L, I and V.

(after doing the previous one, I just remembered a few things)
Choose your code carefully
An example, to try and explain what this mean.
Ajax:
 You are as warm as a big red rich fair cute bold cat!

and
Ajax:
 Thou art as blossoming as an embroidered trustworthy bottomless peaceful charming handsome chihuahua!

produce the exact same result, which is make the character being spoken to assume the value 64 (since, assuming you read my long battle with SPL, you know that both lines are equivalent to 2*2*2*2*2*2*1); however, the first one has 59 bytes, while the second one has a bytecount of 107.
Still, no one is going to be demented enough to enter a code-golf challenge with SPL, so...

Could you use the same adjective multiple times in a description?  E.g. a big big big big big big cat, saving 4 more bytes?  I know it ruins the artistry... but this is code golf after all.  ;)

@DLosc, from what I've seen, there's nothing forbidding you to do that. So... you're a better golfer than me ^_^

Ahem. Don't call Robert Fraser demented. http://codegolf.stackexchange.com/a/69360/43394

Remove unneeded words
Look at this (inserting newlines and whitespace for readability):
Puck:You is a big big cat!
     Open your heart!
Ajax:Be you worse than I?
     If so, let us return to Scene V!
     If not, you is a cat.
     You is the sum of I and the sum of a cat and you
     Speak thy mind!
     [Exeunt]

Looks pretty golfed eh? Here's an even more stripped down unintelligible form:
Puck:You big big cat!
     Open heart!
Ajax:Be you worse I?
     If solet usScene V!
     If notyou cat.
     You is the sum ofI the sum ofa cat you.
     Speak thy!

Try it online!
For reference, here's a list of easily removable words from code:

Speak thy mind  -> Speak thy
Open your heart -> Open heart *
Listen to thy heart -> Listen tothy
Open your mind -> Open mind *
You is a cat    -> You cat *
Only applies to constants such as big cat, otherwise you still need the 'is'
Let us return to   -> Let us
Be X [op] than Y?      -> Be X [op] Y?
You is [op] of X -> You is [op] ofX
You is [op] of X and Y -> You is [op] ofX Y
[Exeunt]        -> (removed entirely)

Legend:

X and Y are constants like cat, I or you
[op] are operations like nicer, the sum of
* means you can remove the punctuation if it's the last sentence of the play

If I come across any others I'll add it to the list.
For extra reference, here's the shortest header to start off a program:
,.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]

Try it online!
Add Page and Ford as extra characters as necessary.

If you need even more characters, there's a list here

Use short words
So here they are:

Use a instead of an or the, except the expressions the sum of and similar, since they won't work with a.
Use am, be or is instead of are or art.
Use I instead of me or myself.
Use you instead of thee, thou, thyself or yourself.
Use big for adjectives.
Use cat for positive numbers.
Use pig for negative numbers.
Use zero for zero.
Use worse for A < B (instead of smaller or punier).
Use nicer for A > B (instead of better, bigger, fresher, friendlier or jollier).
Character names:

4 letters: Ajax, Ford, Page, Puck
5 letters: Egeus, Helen, Julia, Lucio, Mopsa, Paris, Pinch, Priam, Regan, Robin, Romeo, Timon, Titus, Venus, Viola
6 letters: Adonis, Aegeon, Alonso, Angelo, Arthur, Banquo, Bianca, Brutus, Cicero, Dorcas, Duncan, Emilia, Fenton, Hamlet, Hecate, Hector, Helena, Hermia, Imogen, Juliet, Lennox, Oberon, Olivia, Orsino, Portia, Thaisa, Thurio, Tybalt
7 letters: Adriana, Aemilia, Agrippa, Antonio, Capulet, Cassius, Claudio, Dionyza, Escalus, Goneril, Horatio, Leonato, Luciana, Macbeth, Macduff, Malcolm, Mariana, Miranda, Octavia, Ophelia, Orlando, Othello, Pantino, Proteus, Publius, Shallow, Shylock, Slender, Solinus, Theseus, Titania, Troilus, Ulysses
8 letters: Achilles, Beatrice, Benedick, Benvolio, Claudius, Cordelia, Cressida, Dogberry, Don John, Falstaff, Gertrude, Hermonie, Isabella, Lysander, Mercutio, Montague, Pericles, Polonius, Pompeius, Prospero, Rosalind, Stephano
9 letters: Agamemnon, Antiochus, Autolycus, Balthazar, Brabantio, Cassandra, Cleopatra, Cornelius, Demetrius, Desdemona, Donalbain, Don Pedro, Ferdinand, Francisca, Hippolyta, King John, King Lear, Lychorida, Sebastian, The Ghost, Valentine, Vincentio
10 letters: Andromache, Cymberline, Fortinbras, Friar John, King Henry
11 letters: Mark Antony
12 letters: Doctor Caius, King Richard, Lady Capulet, Lady Macbeth, Lady Macduff, Prince Henry, Queen Elinor
13 letters: John of Gaunt, Julius Caesar, Lady Montague, Mistress Ford, Mistress Page
14 letters: Friar Laurence, The Apothecary
15 letters: Christopher Sly, Octavius Caesar
17 letters: John of Lancaster, Mistress Overdone, The Duke of Milan
18 letters: The Duke of Venice
24 letters: The Abbot of Westminster
28 letters: The Archbishop of Canterbury
If you really need more, you definitely should consider using the stack of each character.

Note that multi-word characters can omit any spaces after their name (from user202729's tip), so they are preferable to characters with only one word

Use only one scene
Normally, you can't reuse the first scene of an act, since it always has [Enter Ajax and Puck] first thing. However, you can preface this with [Exeunt] to be able to reuse the first scene of a play. [Exeunt] is one byte shorter than declaring a new scene, and jumping to an Act is two bytes less than jumping to a Scene.
E.g: A simple cat program
,.Ajax,.Page,.Act I:.Scene I:.[Enter Page and Ajax]Scene V:.Ajax:Open mind!Speak thy!Let usScene V!

Try it online!
To:
,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Speak thy!Let usAct I!

Try it online!

You don't have to switch people in conditionals.
For example,
Ajax:Is you better than the sum of a fat fat fat fat cat and a fat cat?
Puck:If so,let us return to Scene I.

is longer than
Ajax:Is you better than the sum of a fat fat fat fat cat and a fat cat?If so,let us return to Scene I.

Jumps can be shorter
You can use return to even if the scene is ahead, and vice versa. In fact, the interpreter doesn't even care if you omit it entirely. This means these four statements are 100% equivalent:
Let us proceed to Scene X.
Let us return to Scene X.
Let us Scene X.
Let usScene X.

Jo King (https://codegolf.stackexchange.com/a/164394/76162) has found that "Let us Scene X" is enough.

@EdWynn good to know. I rewrote the answer to include this.

Let usscene X is enough.

Remove redundant spaces
Apart from the trivial ones (two adjacent spaces, adjacent to a punctuation, adjacent to a newline, at the end) (with some exceptions), the space after the following tokens can be removed:

the sum of
let us
the ghost (like this) (but who would use this character anyway)
if so and if not (remove the , after this, and don't need to add any space. Example: if solet usact I)
listen to (so listen tothy works, like this)
and basically any multi-word tokens.

Note: This does not work with the Perl interpreter. It's probably just an unintended effect caused by Flex's parsing behavior. The "language standard" is not clear about that.

Time to back and edit some of my answers... Very nice find!

Is that a bug in the tokenizer, or is that behavior defined in the language?

@Cœur See update.

The "let us return to scene X" can be used even if the character being spoken to is off stage. So instead of:
Puck:Am I as fat as the sum of a big big big big big big cat and a cat?
Ajax:If not,let us return to scene III.
[Exit Puck]
[Enter Page]
Ajax:You is a big big big big big big cat.

You can do:
Puck:Am I as fat as the sum of a big big big big big big cat and a cat?
[Exit Puck]
[Enter Page]
Ajax:If not,let us return to scene III.You is a big big big big big big cat.

If (so|not) does not have to immediately follow the comparison.
Am I as big as you?You big big big big big cat.If so, you is the sum of you and a big big cat.

In fact, the results of a comparison are stored as a flag and can be used repeatedly across scene transitions or across several If sos. This can be helpful in avoiding repeating comparisons!

Instead of substracting, add constants
You is the difference between I and a big cat.

is longer than
You is the sum of I and a big pig.

Use 'square', 'cube', 'product' and 'factorial'
The operations the square of, the cube of, the factorial of and the product of exist but are only mentioned in passing (if at all) in the documentation. They can save you bytes to define (large-ish) constants. For instance, to get the number 64,
a big big big big big big cat

is 5 bytes longer than
the cube ofa big big cat

Similarly, the shortest way of getting 49 is with \$49=7^2\$ i.e.
the square ofthe sum ofa big big big cat a pig

and you can get 24 as \$4!\$ i.e.
the factorial ofa big big cat

There can be situations where viewing a number as the product of two smaller existing constants can make the product of useful.
Finally, note that there is also the square root ofand the quotient between. Both round down, as the only type in SPL is integers: a short way to get 200 is as \$200 = \lfloor \sqrt{8!} \rfloor\$:
the square root ofthe factorial ofa big big big cat

Use shorter words
Examples:
Thy and thyself are shorter than your and yourself.
Is is shorter than are.
and more...

Gotos aren't the only commands usable with If (so|not)
Am I as big as you?If so,you is the sum of you and a big big cat.If not,you is the sum of you and twice I.

All newlines are ignored
,.Ajax,.Puck,.Page,.Act:.Scene:.[Enter Ajax and Puck]Ajax:You Puck.[Exeunt]

You don't need the ending . or !.
Try it online!
This can also be used before a [. (thanks jimmy23013)
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You cat[Exeunt]

Examples:

,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You cat
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Open mind[Exeunt]

Doesn't work in:

,.Ajax,.Page,.Act I:.Scene I:[Enter Ajax] (right after Scene {number}:) (however this works, I don't know why)
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen to your heart (and shorter variants)
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Let us return to scene I (and shorter variants)
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Recall (only after empty Recall, Recall x or Recall@ etc. works)
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Speak thy (without mind)

This doesn't to work in some situations where you've already removed a word, such as Speak thy or Let us Scene I

Use ‘twice’ and the distributive property
Instead of:
You is the sum ofa big big big big cat a big big big cat.

Use:
You is twice twice twice the sum ofa big cat a cat.

This saves 2 bytes per twice since 2 uses of big is 8 bytes (counting spaces) and twice is only 6 bytes.

Use < or > instead of ==
Not applicable to every situation, but it's quite a bit shorter:
Puck == Ajax
Puck:Is I as bad as you?

Puck < Ajax or Puck > Ajax
Puck:Is I worse you?
Puck:Is I nicer you?

4 bytes shorter for both!