text:
ASCII art 3D StreetView
Input:

You get a series of integers (fed via stdin or prompt).
Every pair of integers in this series represents a building's
WIDTH [valid range: 1..10] and HEIGHT [valid range: 0..10]
Assume input to be well-formed.

Sample input (the second line is for demonstration purposes only):

1 2 1 1 1 0 2 4 1 3 1 2 2 1
W H W H W H W H W H W H W H

Corresponding sample output:

                 ______
               /______ /|
              |       | |__
              |       |/__ /|
     __       |       |   | |__
   /__ /|     |       |   |/__ /|
  |   | |__   |       |   |   | |______
  |   |/__ /| |       |   |   |/______ /|
  |   |   | |_|       |   |   |       | |
  |_o_|_o_|/__|_o_____|_o_|_o_|_o_____|/
  -------------------------------------
 -  -  -  -  -  -  -  -  -  -  -  -  -
-------------------------------------

Rules:
The buildings

A basic building block looks like this (1 W, 1H)

   __
 /__ /| (base cube is borrowed from the one at this question:
|   | |  http://stackoverflow.com/questions/1609702/code-golf-playing-cubes)
|___|/

Our view is (ahum) ~3D so neighbouring buildings may hide parts of others.
Buildings are 'logically' rendered from left to right.
The first building is preceded by two spaces to it's left.
You render every building by applying the WIDTH and HEIGHT
to the dimensions of the base cube (do have a look at the sample output provided!).
For reference: number of characters from the left to the right 'wall' (for a building with W > 1): (W*5)-(W-1).
Buildings with Height > 0 have ONE door (which is depicted by the character o and is
located at two characters from the 'left' wall on the 'bottom' row ).

The road:

The road consists of three parts which we'll call 'top', 'middle' and 'bottom'.
The 'top' part and 'bottom' part are identical apart from the fact that
the 'top' part is preceded by two spaces.
The middle part is preceded by one space and consists of a repetition of the
following pattern: '-  '
Length is to be determined by the total width of the combined buildings: the most rightmost part of the road corresponds with the position of the 'right' wall of the 'last' building.

Winners:
This is code-golf! The winner is the qualifying contestant with the shortest solution (by source code count). The source must consist solely of printable ASCII characters. Have fun!
Imaginary bonus points for (random) windows, cars or pedestrians.
Feel free to comment if the specifications are not clear!

@user unknown: there was indeed a small typo in the rules indeed. Should be fixed now, thanks!

Trailing whitespace permitted? You seem to have some in the example, so I assume so.

@Peter Taylor: trailing whitespace is allowed.

Road part 3, should that be '-  ' (with two spaces)? Edit: Ah, the two spaces don't show :P.  You can display multiple spaces by using ASCII 255 (non-breaking space, ALT+255 on numpad), or by copying and pasting from my comment here. Orr... you could instead just say it's a repetition of ' - ' :)

It looks like the height valid range is actually [0..10].  Also what do you mean by but you must not enforce this in 3)?  IMO, any assumption is available to be exploited if it increases your score. So I may write code that only works if the total width is less than 80 if I can squeeze out a lower character count.  For example, writing output to a display buffer array with a width of 80, so it will crash on any higher total width.  If you want any width supported, then don't give the assumption - you can't have both :P

@mellamokb: thanks for commenting! (spaces and range fixed). You may write code that only works if the total width is less than 80, that was what I was trying to convey. But you are right, I'll delete part of the assumption.

Haskell, 396 characters
w&h=take h((3," /|"++(w-3)#'_'++"o_|"):c[(3,"| |"++(w-1)#s++"|")])++[(2,"|/ "++(w-2)#'_'++"/"),(0,"  "++(w-2)#'_')]++c[(0,w#s)]
p(w,h)=r.z take[sum w+k|k<-[1..]]$([c"-",s:c"-  ","  "++c"-"]++).map r.foldl(z(%))((2+maximum h)#(5#s))$z(&)w h
main=interact$unlines.p.q.map read.words;y%(d,x)=x++drop d y;q(x:y:z)=(4*x:a,2*y:b)where(a,b)=q z
q x=(x,x);(#)=replicate;c=cycle;r=reverse;z=zipWith;s=' '

Example output:
$ runghc Streetview.hs <<< "1 1 1 3 1 2 1 0 2 4 2 2 1 3 3 1"
                     ______
                   /______ /|
         __       |       | |        __
       /__ /|     |       | |      /__ /|
      |   | |__   |       | |_____|   | |
      |   |/__ /| |       |/______|   | |
     _|   |   | | |       |       |   | |__________
   /__|   |   | | |       |       |   |/__________ /|
  |   |   |   | |_|       |       |   |           | |
  |_o_|_o_|_o_|/__|_o_____|_o_____|_o_|_o_________|/
  -------------------------------------------------
 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
-------------------------------------------------

+1 Your recent haskell submissions on codegolf.se have triggered an interest in me for learning a bit more about haskell. Short as the solutions may be, they still remain quite 'readable' imho.

Python, 415 chars
I=eval(raw_input().replace(' ',','))
X=I[::2]
Y=I[1::2]
W=4*sum(X)+6
H=2*max(Y)+2
A=W*H*[' ']
p=W*H-W+2
for w,h in zip(X,Y):i=2*h;j=4*w;q=p-i*W;r=p+j;s=q+j;A[p+1:q+1:-W]=A[p+2:q+2:-W]=i*' ';A[p:q:-W]=A[r:s:-W]=A[r+2-W:s+2-W:-W]=i*'|';A[p+1:r]='_'*(j-1);A[q+2:s]=A[q+3-W:s+1-W]='_'*(j-2);A[q+1]=A[s+1]=A[r+1]='/';A[p+2]='_o'[h>0]; p+=j
A[W-1::W]='\n'*H
D=(W-5)*'-'
print''.join(A)+'  '+D+'\n'+(' - '*W)[:W-4]+'\n'+D

Uses slices to draw all the parts of the building.
$ echo "1 2 1 1 1 0 2 4 1 3 1 5 2 1" | ./streetview.py
                             __
                           /__ /|
                 ______   |   | |
               /______ /| |   | |
              |       | |_|   | |
              |       |/__|   | |
     __       |       |   |   | |
   /__ /|     |       |   |   | |
  |   | |__   |       |   |   | |______
  |   |/__ /| |       |   |   |/______ /|
  |   |   | |_|       |   |   |       | |
  |_o_|_o_|/__|_o_____|_o_|_o_|_o_____|/
  -------------------------------------
 -  -  -  -  -  -  -  -  -  -  -  -  -
-------------------------------------

+1 Very nice. The solution looks pretty golfed already ;-)

There's one lost space at  p+=j (@the end of the long line). Not sure if you counted that one ;-)


text:
Outputting ordinal numbers (1st, 2nd, 3rd)
I would like to generate (as a return result of a function, or simply as the output of a program) the ordinal suffix of a positive integer concatenated to the number.
Samples:
1st
2nd
3rd
4th
...
11th
12th
13th
...
20th
21st
22nd
23rd
24th

And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over.
The input would be the number and the output the ordinal string as shown above.
What is the smallest algorithm for this?

Hi, NickC, and welcome to codegolf.SE!  Just to clarify, do you mean that we should read a number like 11 as input, and output e.g. 11th?  Is each number in the input on a separate line, and should the output numbers be on separate lines too?  And do we need to handle more than one line of input?

Are you looking for smallest algorithm or smallest code?

@Ilmari I am looking for 11 as input and 11th as output.  I don't mind if it processes multiple lines but what I had in mind was processing just a single number.

@M42 You know, I'm not really sure. I don't have a strict requirement - but I was probably thinking smallest algorithm.

Perl, 37 + 1 characters
s/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg

This is a regexp substitution that appends the appropriate ordinal suffix to any numbers in $_ that are not already followed by a letter.  To apply it to file input, use the p command line switch, like this:
perl -pe 's/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg'

This is a complete Perl program that reads input from stdin and writes the processed output to stdout.  The actual code is 37 chars long, but the p switch counts as one extra character.
Sample input:
This is the 1 line of the sample input...
...and this is the 2.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
101 102 103 104 105 106 107 108 109 110

Output:
This is the 1st line of the sample input...
...and this is the 2nd.
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
11th 12th 13th 14th 15th 16th 17th 18th 19th 20th
21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th
101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th

Numbers already followed by letters will be ignored, so feeding the output again through the filter won't change it.  Spaces, commas and periods between numbers are not treated specially, so they're assumed to separate numbers like any other punctuation.  Thus, e.g. 3.14159 becomes 3rd.14159th.
How does it work?

First, this is a global regexp replacement (s///g).  The regexp being matched is 1?\d\b, where \d matches any digit and \b is a zero-width assertion matching the boundary between an alphanumeric and a non-alphanumeric character.  Thus, 1?\d\b matches the last digit of any number, plus the previous digit if it happens to be 1.
In the substitution, which is evaluated as Perl code due to the /e switch, we take the matched string segment ($&) and append (.) to it the suffix obtained by using $& itself as an integer index to the list (0,st,nd,rd); if this suffix is zero or undefined (i.e. when $& is zero or greater than three), the || operator replaces it with th.

Edit: If the input is restricted to a single integer, then this 35 character solution will suffice:
s/1?\d$/$&.((0,st,nd,rd)[$&]||th)/e

Should be able to drop the g off the substitution if you specify that each number must be on it's own line.  Also, that'd let you change the word boundary to be $.  But overall, +1, damn clever solution.

@GigaWatt: Indeed, I wrote the code before NickC answered my question about the input format, so I made it as generic as possible.

I know this is pretty old and rules were different, but using $\  instead of s/// shaves a few bytes off: Try it online!

In fact, even shorter using /.../g syntax: Try it online!

Python 2, 49 bytes
lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4]

An anonymous function. A full program would be counted at 55 bytes.
'tsnrhtdd'[i::4] encodes the suffixes th st nd rd for values of i from 0 to 3. Given this, all we need is a way to map the values of n to the index of the corresponding suffix, i. A straightforward expression that works is (n%10)*(n%10<4 and not 10<n%100<14). We can easily shorten this by dropping the first set of parentheses and observing that n%5 gives the same results as n%10 for the values of n with the special suffixes. With a bit of trial and error, one may also shorten not 10<n%100<14 to n%100^15>4, which can be chained with the other conditional to save even more bytes.

this is some black magic right here c:

http://www.terminally-incoherent.com/blog/wp-content/uploads/2012/08/areyouawizard.png

the straightforward expression looks to have a mistake: the index should be non-zero if n%100 is not between 10 and 14.

@jeje Good eye! I fixed up the explanation. Funny how this error has gone unnoticed for so many years.

Python, 68 characters
i=input()
k=i%10
print"%d%s"%(i,"tsnrhtdd"[(i/10%10!=1)*(k<4)*k::4])

This is really late, but you can take off 7 bytes by doing \i`+"tsnrhtdd"`. Otherwise, this is the exact solution I just got.

Mathematica 39 45 bytes
Note: In recent versions of Mathematica, asking for the nth part of p, where p is undefined, generates an error message,  but returns the correct answer anyway.  I've added Quiet to prevent the error message from printing.
Quiet@StringSplit[SpokenString[p[[#]]]][[2]]&

Usage
Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &[31]

31st

Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &/@Range[21]

{"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th",
  "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th",
  "18th", "19th", "20th", "21st"}

How it works
SpokenString writes out an any valid Mathematica expression as it might be spoken. Below are two examples from the documentation for SpokenString,
SpokenString[Sqrt[x/(y + z)]]

"square root of the quantity x over the quantity y plus z" *)

SpokenString[Graphics3D[Sphere[{{0, 0, 0}, {1, 1, 1}}]], "DetailedGraphics" -> True]

"a three-dimensional graphic consisting of unit spheres centered at 0, 0, 0 and 1, 1, 1"

Now, for the example at hand,
Quiet@SpokenString[p[[#]]] &[31]

"the 31st element of p"

Let's represent the above string as a list of words:
StringSplit[%]

{"the", "31st", "element", "of", "p"}

and take the second element...
%[[2]]

31st

I'm confused; where is p defined?  EDIT: never mind, I see how you're using this; unfortunately it does not work on my system. :-/

It works on v.9.0.1. (I seem to recall that you are using 7.0.)  Yes, p does not need to be defined.

I understand that now.  However, in v7 I get from SpokenString @ p[[117]] the output " part 117 of p".

So SpokenString gets revised from time to time. I wouldn't be surprised it this code (http://codegolf.stackexchange.com/questions/8859/hello-world-in-1024-characters/8869#8869) also doesn't work on v. 7. BTW, it wasn't meant to be an enduring solution.

Hah, I hadn't seen that answer before.

Actually, I haven't seen a lot of your contributions to this site.  You're really going crazy here! (In a good way.)

Javascript (ES6) 50 44 Bytes
a=>a+=[,"st","nd","rd"][a.match`1?.$`]||"th"

Notes

takes imput as a string
Removed 6 bytes, thanks @user81655

a+ -> a+=, remove parentheses, \d -> ., remove [0], and if you take the number as a string: a.match\1?.$`instead of/1?.$/.exec(a)`.

Ruby, 60
It's not as good as the Perl entry, but I figured I'd work on my Ruby skills.
def o(n)n.to_s+%w{th st nd rd}[n/10%10==1||n%10>3?0:n%10]end

Function takes one integer argument, n, and returns a string as the ordinal form.
Works according to the following logic:
If the tens digit is a 1 or the ones digit is greater than 3 use the suffix 'th'; otherwise find the suffix from the array ['th', 'st', 'nd', 'rd'] using the final digit as the index.

o(113) is "113rd", should be "113th". The tens digit check doesn't account for numbers with more than two digits.

Ok, pitched in another %10 to compensate.  Added 3 characters.  (I feel like %10 appears enough where it should be shortened somehow, but I can't think of a solution)

You can never beat Perl in writing horrible incomprehensible code that's as short as possible :)

Set a variable to 10?

I think setting a variable to n%10 is better.

Javascript, 68 71
function o(n){return n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th')}

Joint effort with ItsCosmo.
EDIT: Wasn't working properly with numbers > 100

You could bring it down to 62 with: function o(n)n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th') and you can bring it down further to 54 if you are happy to use fat arrow notation: o=n=>n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th')

@WallyWest For some reason, I really like that my solution works in modern browsers. Feel free to post your own answer; I think its sufficiently different.

No, that's fine! Just providing a few alternatives!

I made it work with ARGV: for(n of arguments)print(n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th'))

JavaScript, 64 characters (ES3) or 47 characters (ES6)
ES3 (64 characters):
function(n){return n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'}
ES6 (47 characters):
n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'
Explanation
The expression n % 100 >> 3 ^ 1 evaluates to 0 for any positive n ending with digits 08–15. Thus, for any n mod 100 ending in 11, 12, or 13, the array lookup returns undefined, leading to a suffix of th.
For any positive n ending in other digits than 08–15, the expression n % 100 >> 3 ^ 1 evaluates to a positive integer, invoking the expression n % 10 for array lookup, returning st,nd, or rd for n which ends with 1, 2, or 3. Otherwise, th.

Save a bytes with n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'.

@Shaggy, thanks, updated as suggested.

FYI https://github.com/guest271314/SpeechSynthesisSSMLParser/blob/master/SpeechSynthesisSSMLParserTest.html#L64, https://github.com/guest271314/SpeechSynthesisSSMLParser/blob/master/SpeechSynthesisSSMLParserTest.html#L65

@guest271314, fun to see this code being used. Note that it only works for positive numbers, another alternative is n+=[,"st","nd","rd"][(((n<0?-n:n)+90)%100-10)%10]||"th", adapted from this post.

Haskell, 95 100 chars
h=foldr g"th".show
g '1'"th"="1st"
g '2'"th"="2nd"
g '3'"th"="3rd"
g '1'[x,_,_]='1':x:"th"
g a s=a:s

Testing:
*Main> map h [1..40]
["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13t
h","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th",
"25th","26th","27th","28th","29th","30th","31st","32nd","33rd","34th","35th","36
th","37th","38th","39th","40th"]

Must be loaded with -XNoMonomorphismRestriction.

I'm seeing 100 here, but 95 using an infix operator.

thanks, fixed. probably didn't know we have to count the newlines as well, back then.

J -  44  41 char
Nothing in J? This is an outrage!
(":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)

Explained (note that 1 is boolean true in J and 0 is false):

100&| - First, reduce the input modulo 100.
10(|*|~:-~) - In this subexpression, | is the input mod 10 and -~ is the input (mod 100) minus 10. You don't get many trains as clean as this one in J, so it's a treat to see here!

~: is not-equals, so |~:-~ is false if the tens digit is 1 and true otherwise.
* is just multiplication, so we're taking the input mod 10 and multiplying by a boolean, which will zero it out if false. The result of this is "input mod 10, except 0 on the tens".

4|4<. - Min (<.) the above with 4, to clamp down larger values, and then reduce modulo 4 so that they all go to zero.
th`st`nd`rd{::~ - Use that as an index into the list of suiffixes. Numbers ending in X1 or X2 or X3, but not in 1X, will find their suffix, and everything else will take the 0th suffix th.
":, - Finally, take the original input, convert it to a string (":), and append the suffix.

Usage is obvious, though as-is the verb can only take one ordinal, not a list.
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 112         NB. single use
112th
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 1 2 3 4 5   NB. doing it wrong
|length error
|       (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)1 2 3 4 5
   NB. i.5 10   makes a 5x10 grid of increasing integers
   NB. &.>      to operate on each integer separately, and box the result after
   (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)&.> i.5 10   NB. all better
+----+----+----+----+----+----+----+----+----+----+
|0th |1st |2nd |3rd |4th |5th |6th |7th |8th |9th |
+----+----+----+----+----+----+----+----+----+----+
|10th|11th|12th|13th|14th|15th|16th|17th|18th|19th|
+----+----+----+----+----+----+----+----+----+----+
|20th|21st|22nd|23rd|24th|25th|26th|27th|28th|29th|
+----+----+----+----+----+----+----+----+----+----+
|30th|31st|32nd|33rd|34th|35th|36th|37th|38th|39th|
+----+----+----+----+----+----+----+----+----+----+
|40th|41st|42nd|43rd|44th|45th|46th|47th|48th|49th|
+----+----+----+----+----+----+----+----+----+----+

Alternative 41 char solution showing off a couple logical variants:
(":;@;st`nd`rd`th{~3<.10(|+3*|=-~)100|<:)

Previously I had an overlong explanation of this 44 char hunk of junk. 10 10#: takes the last two decimal digits and /@ puts logic between them.
(":,th`st`nd`rd{::~10 10(]*[(~:*])4>])/@#:])

Golfscript, 34 characters
~.10/10%1=!1$10%*.4<*'thstndrd'2/=

Javascript, 75 60
With the new arrow notation:
o=(s)=>s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")

Old version, without arrow notation (75 chars):
function o(s){return s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")}

52 bytes (V8)

APL (Dyalog Unicode), 38 36 bytes
Thanks to ngn for fixing a bug while maintaining byte count.
Anonymous tacit prefix function. Requires ⎕IO (Index Origin) set to 0, which is default on many systems. Even works for 0!
⍕,{2↑'thstndrd'↓⍨2×⊃⍵⌽∊1 0 8\⊂10↑⍳4}

Try it online!
{…} anonymous lambda; ⍵ is argument:
 ⍳4 first four ɩndices; [0,1,2,3]
 10↑ take first ten elements from that, padding with zeros: [0,1,2,3,0,0,0,0,0,0]
 ⊂ enclose to treat as single element; [[0,1,2,3,0,0,0,0,0,0]]
 1 0 8\ expand to one copy, a prototypical copy (all-zero), eight copies;
  [[0,1,2,3,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0],
   [0,1,2,3,0,0,0,0,0,0],
   [0,1,2,3,0,0,0,0,0,0],
   ⋮ (5 more)
   [0,1,2,3,0,0,0,0,0,0]]
 ∊ ϵnlist (flatten);
  [0,1,2,3,0,0,0,0,0,0,
   0,0,0,0,0,0,0,0,0,0,
   0,1,2,3,0,0,0,0,0,0,
   0,1,2,3,0,0,0,0,0,0,
   ⋮ (50 more)
   0,1,2,3,0,0,0,0,0,0]
 ⍵⌽ cyclically rotate left as many steps as indicated by the argument
 ⊃ pick the first number (i.e. the argument-mod-100'th number)
 2× multiply two by that (gives 0, 2, 4, or 6)
 'thstndrd'↓⍨drop that many characters from this string
 2↑ take the first two of the remaining characters
⍕, concatenate the stringified argument to that

"31th"?

⍕,{2↑'thstndrd'↓⍨2×⊃⍵⌽∊1 0 8\⊂10↑⍳4}

sorry, I forgot to mention ⎕io←0. I can see you guessed that, but there are a few 1,2,3,4,0,0... that should be 0,1,2,3,0,0...

@ngn Fixed. And happens to work for 0 too!

R, 79 76 bytes
Since there is no R solution yet... no tricks here, basic vector indexing, golfed down 3 chars thanks to Giuseppe. Previously tried index: [1+(x%%10)-(x%%100==11)] and [1+(x%%10)*(x%%100!=11)].
function(x)paste0(x,c("th","st","nd","rd",rep("th",6))[1+x%%10*!x%%100==11])

Try it online!
With substr, 79 bytes:
function(x,y=1+2*min(x%%10-(x%%100==11),4))paste0(x,substr("thstndrdth",y,y+1))

Try it online!

1+x%%10*!x%%100==11 for the index?

@Giuseppe I need to calm down on the parenthesis :). Clever use of ! in front of expression instead of !=.

Yeah, the operators have weird precedence; ^ is really high, then %%-type operators, then */ and +- and I think == and &| comes next. ! has quite low precedence so you can use it as a separator between operations.

Bash (Cardinal to ordinal) 91 Bytes:
function c(){ case "$1" in *1[0-9]|*[04-9])"$1"th;;*1)"$1"st;;*2)"$1"nd;;*3)"$1"rd;;esac }

You can save at least 2 bytes in your solution, just rename your c2o function something with a 1-byte name.

58 bytes.

Wow @tailsparkrabbitear I think you should write an answer. Or do you want me to edit my answer?

If you say so; posted mine.

PowerShell, 92
process{"$_$(switch -r($_){"(?<!1)1$"{'st'}"(?<!1)2$"{'nd'}"(?<!1)3$"{'rd'}default{'th'}})"}

Works with one number per line of input. Input is given through the pipeline. Making it work for only a single number doesn't reduce the size.

PHP, 151
I know that this program is not comparable to the others. Just felt like giving a solution.
<?$s=explode(' ',trim(fgets(STDIN)));foreach($s as$n){echo$n;echo(int)(($n%100)/10)==1?'th':($n%10==1?'st':($n%10==2?'nd':($n%10==3?'rd':'th')))."\n";}

you can save a few characters by using foreach($s as $n){echo$n;

K - 44 char
It so happens that this is exactly as long as the J, and works in almost the same way.
{x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}

Explained:

x$: - First, we convert the operand x into a string, and then assign that back to x. We will need its string rep again later, so doing it now saves characters.
.:' - Convert (.:) each (') digit back into a number.
-2#0, - Append a 0 to the front of the list of digits (in case of single-digit numbers), and then take the last two.
{y*(y<4)*~1=x}. - Use the two digits as arguments x and y to this inner function, which returns y if y is less than 4 and x is not equal to 1, otherwise 0.
`th`st`nd`rd@ - Index the list of suffixes by this result.
x,$ - Convert the suffix from symbol to string, and append it to the original number.

Usage:
  {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} 3021
"3021st"
  {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}' 1 2 3 4 11 12 13 14  /for each in list
("1st"
 "2nd"
 "3rd"
 "4th"
 "11th"
 "12th"
 "13th"
 "14th")

PHP, 98 bytes
function c($n){$c=$n%100;$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];}

The 11-13 bit is killing me here.  Works for any integer $n >= 0.
For any integer $n:
PHP, 103 bytes
function c($n){$c=abs($n%100);$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];}

Javascript ES6, 52 chars
n=>n+(!/1.$/.test(--n)&&'snr'[n%=10]+'tdd'[n]||'th')

C#, 62 bytes
n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd");

Full program and verification:
using System;

namespace OutputOrdinalNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,string>f= n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd");

            for (int i=1; i<=124; i++)
                Console.WriteLine(f(i));
        }
    }
}

You can golf it by two bytes by changing the || to |.

Mathematica 29 + 5 = 34 bytes
SpokenStringDump`SpeakOrdinal

+5 bytes because Speak function must be called before using this built-in.
Usage
SpokenStringDump`SpeakOrdinal[1]

"1st "

SpokenStringDump`SpeakOrdinal[4707]

"4,707th "

Java 7, 91 81 bytes
String d(int n){return n+(n/10%10==1|(n%=10)<1|n>3?"th":n<2?"st":n<3?"nd":"rd");}

Port from @adrianmp's C# answer.
Old answer (91 bytes):
String c(int n){return n+((n%=100)>10&n<14?"th":(n%=10)==1?"st":n==2?"nd":n==3?"rd":"th");}

Ungolfed & test code:
Try it here.
class M{
  static String c(int n){
    return n + ((n%=100) > 10 & n < 14
                ?"th"
                : (n%=10) == 1
                   ? "st"
                   : n == 2
                      ? "nd"
                      : n == 3
                         ? "rd"
                         :"th");
  }

  static String d(int n){
    return n + (n/10%10 == 1 | (n%=10) < 1 | n > 3
                 ? "th"
                 : n < 2
                    ? "st"
                    : n < 3
                       ? "nd"
                       :"rd");
  }

  public static void main(String[] a){
    for(int i = 1; i < 201; i++){
      System.out.print(c(i) + ", ");
    }
    System.out.println();
    for(int i = 1; i < 201; i++){
      System.out.print(d(i) + ", ");
    }
  }
}

Output:
1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th,
1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th,

Vyxal, 6 bytes
∆o2NȯJ

Try it Online!

OCaml
I'm pretty new to OCaml, but this is the shortest i could get.
let n x =
   let v = x mod 100 and string_v = string_of_int x in
   let z = v mod 10 in
   if v=11 || v=12 || v=13 then string_v^"th"
   else if v = 1 || z = 1 then string_v^"st" else if v = 2 || z = 2 then string_v^"nd" else if v = 3 || z = 3 then string_v^"rd" else string_v^"th";;

I created a function n that takes a number as a parameter and does the work. Its long but thought it'd be great to have a functional example.

input: 11 would yield output: 11st

yeah, you're right.. I've made the correction. Thanks

I've just tidied up the formatting on your code. Each line needs to be preceded by four spaces in order to be recognized as a code block.

Wouldn't your first if check be shorter as if v>10 && v<14? I'm not familiar with ocaml, but is it necessary to have the string_v variable be so long?

No its not necessary, I could have chosen w or x. Just wanted something meaningful.
But you're right, it would have made the code a little shorter.

Welcome to PPCG! Please include your byte count on the header. (too late?)

Python 2.7, 137 chars
def b(n):
 for e,o in[[i,'th']for i in['11','12','13']+list('4567890')]+[['2','nd'],['1','st'],['3','rd']]:
  if n.endswith(e):return n+o

n should be a string
I know I'm beaten by the competition here already, but I thought I'd provide my idea anyways
this just basically generates a list of key, value pairs with number (as a string) ending e and the ordinal o. It attempts to match 'th' first (hence why I didn't use a dictionary), so that it won't accidentally return 'st', for example, when it should be 'th'. This will work for any positive integer

n[-1]==e is 5 chars shorter than n.endswith(e)

Scala 86
def x(n:Int)=n+{if(n%100/10==1)"th"else(("thstndrd"+"th"*6).sliding(2,2).toSeq(n%10))}

Scala 102:
def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".take(n+1)%5*2.drop(n%5*2))else n+"th"

102 as well:
def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".sliding(2,2).toSeq(n%10))else n+"th"

ungolfed:
def x (n: Int) =
  n + { if (((n % 100) / 10) == 1) "th"
        else (("thstndrd"  + ("th"  * 6)).sliding (2, 2).toSeq (n % 10))
      }

C: 95 characters
A ridiculously long solution:
n;main(){scanf("%d",&n);printf("%d%s",n,n/10%10-1&&(n=n%10)<4&&n?n>2?"rd":n<2?"st":"nd":"th");}

It needs to be mangled more.

A user flagged this saying "is incorrect: doesn't loop at all, i.e. it works just for a given number, not all numbers below it. see ideone.com/pO6UwV ." That's not a reason to flag as moderators do not judge correctness, but it may be an issue.

Based upon this comment from the question creator: "@Ilmari I am looking for 11 as input and 11th as output. I don't mind if it processes multiple lines but what I had in mind was processing just a single number. – NickC Jan 20 '12 at 21:00" it is doing what it should.
I.e. it only should process a single number.

sorry for that flag; I misread the requirement, and didn't have enough rep at the time, to comment directly. Sorry again. :)

Haxe, 83 chars
function o(n:Int){return ['th','st','nd','rd'][n%100>20||n%100<4?n%10>3?0:n%10:0];}

Based on the javascript version, fixed for n > 100 as well.

Two suggestions: 1) Remove all whitespace to save some bytes. Right now, I count 91 total. 2) This doesn't seem to be a full program or a function. Perhaps you should consider turning it into one of those.

yeah, but thats quite straightforward, so I tried to stay readable.

yeah, you're right, I just pasted it here so anyone can use it without reconverting from another lang. :)

C - 95 83 characters
main(n,k){scanf("%d",&n);k=(n+9)%10;printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");}

Degolfed:
main(n,k)
{
    scanf("%d",&n);
    k=(n+9)%10; // xx1->0, xx2->1, xx3->2
    printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");
}

We could do k=(n-1)%10 instead of adding 9, but for n=0 we would get an incorrect behaviour,
because in C (-1)%10 evaluates to -1, not 9.

Javascript, 75
function s(i){return i+'thstndrd'.substr(~~(i/10%10)-1&&i%10<4?i%10*2:0,2)}

Oracle SQL 11.2, 101 bytes
SELECT:1||DECODE(ROUND(MOD(:1,100),-1),10,'th',DECODE(MOD(:1,10),1,'st',2,'nd',3,'rd','th'))FROM DUAL

Python, 88 84 bytes
lambda x:x+((('th','st','nd','rd')+('th',)*6)[int(x[-1])]if('0'+x)[-2]!='1'else'th')

Ungolfed:
def y(x):
    return x + (('th', 'st', 'nd', 'rd') + ('th', ) * 6)[int(x[-1])] if ('0' + x)[-2] != '1' else 'th')

lambda x defines an anonymous function with parameter x. ((('th','st','nd','rd')+('th',)*6)[int(x[-1])] defines a tuple of the endings for numbers less than 10, the 0-th element is for 0, and so forth. the if ('0'+x)[-2] != '1' checks if there is 11, 12, or a 13 to fix, and adds then else 'th' adds th instead of st, rd, or nd.

This is a great answer, but it took me a while to go through and understand it. If you could add a code explanation and breakdown below the golfed version of your code, it would help people learn from your code and improve the quality of your answer.

Ok, I will. Should I also add an un-golfed answer?

It shouldn't be a different answer... What you've done is fine, well done. If you want any more challenges to do, I could give some recommendations.

Ok. You could try... Adjust your chair, or Where will your buddies sit. Or you could try some of my challenges, such as The Knight's Next Tour. If these aren't the sort of challenges you like, just say.

Scala 2.11.7, 151 Chars
def o(x:Int*)=x map{
case a if(a%10)==1&&a%100!=11=>a+"st"
case b if(b%10)==2&&b%100!=12=>b+"nd"
case c if(c%10)==3&&c%100!=13=>c+"rd"
case e=>e+"th"
}

Usage
   o(1,2,3,4) -> ArrayBuffer("1st", "2nd", "3rd", "4th")

Sorry, but all answers need to be golfed. Please golf this, if not than it's invalid and must be deleted.

I'm pretty sure you can remove the space between map and {, : and Int*, and remove the newline between "th" and } (I don't know Scala, so I might be completely wrong). Welcome to PPCG!

Common Lisp, 63
(format t"~a~a"i(let((x(format()"~:r"i)))(subseq x(-(length x)2))))

Input is i. There's probably a more clever way to golf this.

Pyth, 33 bytes
+Q@.>+c"stndrd"2*]"th"7 1?qh`Q\1Z

Try it online!

Procedural Footnote Language, 39 bytes
[1]
[PFL1.0]
[1] [ORD:[INPUT]]
[PFLEND]

The BODY section of the document contains a reference to footnote [1]; footnote [1] contains the [ORD]inal representation of the [INPUT].

JavaScript (Node.js), 51 bytes
credit to @KevinCruijssen for improving the answer
n=>n+=[,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th'

Try it online!

Explanation :
n =>                      // input
    n+=[,'st','nd','rd']     // the array of suffices add everything to n
        [~~(n/10%10)-1?n%10:0] // the full magic
    || 'th'               // works for everything except 1 , 2 , 3 just like what you want

"The full magic". The one bit I actually wanted to read the comments on :)

@SteveBennett The general logic that if the tens digit ((n/10%10), rounded by the ~~) is a one (-1)  then just get the index 0, which maps to th, otherwise get the index of the ones digit, which will be the appropriate suffix for 1,2 and 3, and th otherwise

47

Combining with this is 46 but not not sure which to collect

Julia 0.6, 68 bytes
f(x,m=x%10,p=x%100-m)="$x$(["th","st","nd","rd"][m>3||p==10?1:m+1])"

Try it online!
Straightforward remainder rules in Julia.

05AB1E, 21 bytes
т%T‰ć≠*4ªß…thŠØ3ôsè¨«

Try it online or verify a few more test cases at once.
Explanation:
Mostly ported from a sub-section of this answer of mine, except with additional leading т%.
т%                     # Take modulo-100 on the (implicit) input-integer
  T‰                   # Take the divmod-10 ([n//10,n%10]) on that
    ć                  # Extract the head: n//10
     ≠                 # Check that it's NOT equal to 1 (0 if 1; 1 otherwise)
      *                # Multiply the [n%10] by this
       4ª              # Append a 4 to this list: [n%10*(n//10!=1),4]
         ß             # Pop and push the smallest number in this list
          …thŠØ        # Push dictionary string "th standards"
               3ô      # Split it into parts of size 3: ["th ","sta","nda","rds"]
                 sè    # Index the calculated minimum into this list
                       # (modular 0-based, so both 0 and 4 will index into "th ")
                   ¨   # Remove the last character
                    «  # And append it to the (implicit) input-integer
                       # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why …thŠØ is "th standards".

APL(NARS), 38 chars, 76 bytes
(⍕,{((⍳3)⍳10∣⍵×3≠⌊√⍵)⊃'snrt',¨'tddh'})

test:
  h←(⍕,{((⍳3)⍳10∣⍵×3≠⌊√⍵)⊃'snrt',¨'tddh'})
  h¨0..19
 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th
  h¨20..31
 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 31st
  ⎕fmt h¨100..104
┌5───────────────────────────────────────────┐
│┌5─────┐ ┌5─────┐ ┌5─────┐ ┌5─────┐ ┌5─────┐│
││ 100th│ │ 101st│ │ 102nd│ │ 103rd│ │ 104th││
│└──────┘ └──────┘ └──────┘ └──────┘ └──────┘2
└∊───────────────────────────────────────────┘

I don't think you need the outermost parens (or is it a weak point of NARS?)

@Bubbler I remember without parentesis () does not assign to "h"  name

for me is ok in that way

FEU, 41 bytes
m/1.$/\0th/1$/1st/2$/2nd/3$/3rd/\d$/\0th/

Try it online!

This doesn't work for numbers that end in th unless they have a one as the second last digit. I think you can solve this by adding /\d$/\0th/ to the end. You can also golf the first part to be /1.$/\0th/

@JoKing Thanks for the comment.

C, 87 bytes (correct teen handling)
This C solution is longer than the current shortest 83 byte C solution posted, but as of writing, that 83 byte solution is incorrect and prints numbers like 11st, 12nd, and 13rd.
Here is my solution, which correctly handles teen numbers:
main(n){scanf("%d",&n);printf("%d%s",n,"th\0st\0nd\0rd"+(n%10<4&&n/10%10-1?n%10*3:0));}

Degolfed:
main(n) {
    scanf("%d", &n);
    printf("%d%s", n, "th\0st\0nd\0rd" + (n%10 < 4 && n/10%10 - 1 ? n%10*3 : 0));
}

Bash, 58 bytes
Just a modification of @stephanmg's post in Bash.
Output is on STDERR as in "command not found".
case $1 in
*1?|*[04-9])$1th;;*1)$1st;;*2)$1nd;;*)$1rd
esac

Try it online!
This program completely relies on the limitation that the input is a non-negative decimal integer.

Vyxal, 23 bytes
₀%:4<?₀ḭċ∧*4«∨¦İk√«/$i+

Try it Online!
Explanation:
₀%:4<?₀ḭċ∧*4«∨¦İk√«/$i+    # full program

₀%:                         # push input mod 10 twice
   4<                       # less than 4
     ?₀ḭ                    # input floor div 10
        ċ                   # != 1
         ∧*                 # and both bools, then multiply by initial mod 10
            4«∨¦İk√«/       # "thstndrd" split into 4 parts
                      $i    # indexed by input mod 10
                        +   # concat

Vyxal, 14 bytes
ÞoÞ∞ZƛhṘ2ẎṘntp

Try it Online!
ÞoÞ∞Z          # Zip ordinals with positive integers
     ƛ         # Over each
      hṘ2ẎṘ    # Get the last two characters of the ordinal
           ntp # Append the number

brainfuck, 313 bytes
This was painful. Setup could probably be golfed better. May write a half-decent explanation later.
++++[>++++++<-]>-[<+++++>-]<[->+>+>+>+>+>+>+>+<<<<<<<<]>->--------------->----->--------------->>+>+>----------->>>>+>+>+>,[.>,]<<<[-]>>>-[>+<-----]>---[-<<-<->>>]<<<-[[-]>[->+>++<<]>+<+++++[->-[>]<<<]>[<<<]>[>>[-<<<<<[<]<<<<<[>]<[[->+<]<]>>>>>>>>>[-<<<<<<<<+>>>>>>>>]>>>>>[>]>>>>]<<<]]<<<[<]<<[<]<<<[<]>>>>>>>.>.

Try it online!

Go, 173 110 bytes
import."fmt"
func o(n int){s,k:="th",n%10
if k>0&&k<4&&n/10%10!=1{s=[]string{"st","nd","rd"}[k-1]}
Print(n,s)}

Attempt This Online!

-47 bytes from using slice indexing (by @Steffan)
-14 bytes from outputting to STDOUT (by @Steffan)
-2 bytes from removing duplicate n%10.

Old answer, 173 bytes
import."fmt"
func o(n int)string{s:=Sprint(n)
switch n%100{case 11,12,13:s+="th"
default:switch n%10{case 1:s+="st"
case 2:s+="nd"
case 3:s+="rd"
default:s+="th"}}
return s}

Attempt This Online!

126 bytes

Or 112 bytes by outputting to stdout.

Scratch, idk bytes

I tried to convert it to sb syntax, but it did not work
Try it!
Please comment if you know a way to golf, or byte-count this

It's 295 bytes.

https://codegolf.meta.stackexchange.com/q/673/34718

source: Stack Exchange

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

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

sort: votes


text:
An Old Irish Blessing, reasked (without using encodings)
How much can you golf a program to print "An Old Irish Blessing" without using unprintable ASCII characters?
That restricts us to ASCII characters 32-126 (better still, 32,65-90,97-122 and 13(CR))
For reference that version of the proverb is 205 characters long (excl. newlines).
I'm curious if anything beats Huffman-encoding incl. spaces.

(wondering if anyone else sees a need for a 'no-encodings' tag?)

@Peter: it must use ASCII, and is restricted to characters 32-127. Sound ok?

Seems both reasonable and needed.  Tagged.

I guess someone will compress the bitstring into the ASCII range 32..127 then unpack it, but that's frowned upon. Can anyone get below 100% length otherwise?

Do note that ASCII 127 is not printable.

@ J B I know. Just (32..127) gives a range of 96 values, which will be cleaner than 95 for string manipulation or base-changing. To quibble, we also allowed newline which is ASCII 13.

@smci: ASCII 13 is Carriage Return (CR). Line Feed (LF) aka. newline is ASCII 10 (my answer assumes that's what you meant).

@hammar: yes it was

Golfscript, 198 characters
[]"-!9 4(% 2/!$<)3A50H/ -%%4 9/5
XXXN7).X\"?!,7I3>4UU2I!#+
[[[S35.;(`A[2- 50/.]]]&]%
YO2!U3F|,`/&4ZZZZZK)%,$3
!.$ }4),ze-%%Z!'!k\n-!9 '/S(/]hh )o4(%GG,/7 /&A)3;!v"{.32>{.58<{32+}{56-~1$>2<}if}*+}/+

Output:
$ ruby golfscript.rb blessing.gs
MAY THE ROAD RISE UP TO MEET YOU
MAY THE WIND BE ALWAYS AT YOUR BACK
MAY THE SUN SHINE WARM UPON YOUR FACE
THE RAINS FALL SOFT UPON YOUR FIELDS
AND UNTIL WE MEET AGAIN
MAY GOD HOLD YOU IN THE HOLLOW OF HIS HAND

The poem is compressed to 158 characters by using part of the ASCII range for back-references (of fixed length 2). The coding scheme is as follows:
[10]      : newline (unencoded)
[32]      : space (unencoded)
[33..57]  : literal (33=A, 34=B, ... 57=Y, Z not needed)
[58..126] : back-reference relative to the end of the decompressed string so far.

The remaining 40 characters make up the decompression code which can probably be golfed a little further, since this is my first attempt at Golfscript.

Case-sensitive version, 207 characters
Same concept, but trading some of the back-reference range for lower case letters at the cost of some compression.
[]"-AY THE ROAD RISaUPhO MEET YOU
xxxnWINxB_ALWiS^TuuRiACK
{{{sSUN[HINa{RM UPON}}}F}E
4HoRAuS fLL SOFTzzzzzkIELDS
!NDlNTIwWE MEEzAGAIN
-AY 'OsHOLxYOU k THEggLOW OF (ISeAND"{.32>{.90<{32+}{88-~1$>2<}if}*+}/+

Output:
$ ruby golfscript.rb blessing-casesensitive.gs
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand

{}{stuff}if can be reduced to !{stuff}*. With 33<{}{stuff}if you can save one character more by changing the test to 32>{stuff}*. Also, you can save that penultimate '' because you'll have an empty string on the stack underneath the array, from the empty stdin.

@PeterTaylor: Awesome, thanks :)

And 55\-\.@ can be shortened to 56-~1$. > is an "order" operator, so the array and index can be in either order. However, simply changing \.@ to 1$ causes problems because it's preceded by - and gets tokenised as 55 \ -1 $.

Nice, but how much extra does it cost to make it case-sensitive?

@smci: Using some of the back-reference range for lower case letters means I can't reach as far back, so the compressed length becomes 167 for a total of 207 characters, which isn't as bad as I thought, but still just barely too long.

Perl, 214 characters
s//01road rise2 to 34
01w5d be always at4r back
01s7 sh5e warm284r face
The ra5s fall soft284r fields
And 7til we 3 aga5
0God 6d4 5 1 6low of His hand/;s/\d/('May ','the ',' up',meet,' you',in,hol,un,on)[$&]/eg;say

2 chars shorter if you add encoding 9 for ' fa'

@smci:Thanks, but it's giving the same count.

True, my mistake.

Python, 224 chars
print'''1road rise up to meet you
1wind be always at your back
1sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand'''.replace('1','May the ')

Instead of wasting characters on for loops or multiple replaces, I only have one replace with the single most common combinations of words May the

Python, 263 chars
t="""01road rise2 to34
01w5d be always at4r back
01s7 sh5e warm284r9ce
The ra5s9ll soft284r fields
And 7til we3 aga5
0God 6d4 5 16low of His hand"""

for k,v in enumerate("May ,the , up, meet, you,in,hol,un,on, fa".split(',')):
    t = t.replace(str(k),v)
print t

which was an 'improvement' on my 261-char quick hack, obviously inferior to a simple print.
s="""12road rise up to34
12wind be always at4r back
12sun shine warm54r face
The rains fall soft54r fields
And until we3 again
1God hold4 in 2hollow of His hand"""

for k,v in {1:"May ",2:"the ",3:" meet",4:" you",5:" upon"}.items():
    s = s.replace(str(k),v)
print s

enumerate() takes almost as many chars in creating the dict/sequence, on a short example like this.

I think this is poor in that it takes more characters to generate the blessing than printing the blessing by itself (which is 221 chars)

@Blazer, I remarked exactly that ('obviously inferior to a simple print'). I also remarked that bitpacking would get it smaller (before overhead), since the message has only 28 symbols, thus 4.8 bits of entropy per character. Can you do better (in Python)?

I posted my answer @smci

PHP, 203
Base64 is ASCII only, but I'd still consider this slightly exploitive.
<?=gzinflate(base64_decode('TY5BDsMwCATvecV+hcQkRsWmMras/P8jpW5V9bhidodCN3pmNKOEJs4YT3RDYe64bWzlC0ypCTuDdNLtoHVt2Ol4/BgfFZ6lBk2txJLVD3XSwdvSkFSPqAq3s/8jwpp8o7CM2kUx+fMEXdFZissSsml6FyB1KSOrTdiJLI4c9Rc'));

Proof it works.

Case-sensitive?

That's 171 chars for the string + 32 overhead. I guess this string is too small and non-redundant to break even.

Io, 217 bytes
Compressing the string leads to a longer length...
"May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand"print

Try it online!

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


text:
Play a valid chess move, given a board on stdin
The program plays white.
Example stdin:
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

Example stdout:
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … ♙ … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ … ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

Any valid move is ok. "En passant" and castling are ignored. It is ok to show error messages or print nothing if there is no valid move.
The answer with the most votes wins.

I mean a standard error message caused by failure of some built-in function of the language. So that's ok? — Is it mandatory that the program can do any legal move? Perhaps castling and pawn special moves should be made optional with some bonus?

@leftaroundabout: Whenever you can castle, you can just move the rook instead, so you can skip the logic for that at least.

... and thinking about it some more, the "en passant" move requires information about what previous moves has been made, which cannot be inferred from just the positions of the pieces, so I guess it might be safe to drop that. However, whether the double first move is available can be inferred from the rank of the pawn, so you might want to include that.

@hammar: you're right, I hadn't thought about that. The double move is also not important, except for one case: when you can go two steps you can also go one, so it only becomes important when you're in check and the double-move is the only move that covers the king. Also, even when you don't need to be able to use every move, you still need to consider that black can answer with any possibility.

@hammar "en passant" and castling have to be ignored, there is no such thing as double move in chess as far as I know.

@HristoHristov: I meant the way you can move a pawn 2 steps the first time. Not sure what the proper term is.

@hammar Now I understand. These are two possible moves of the pawn which can be valid or not, so they have to be considered.

Is resigning counted as a legal move? :)

@gnibbler resigning is legal, but it's not a "move" :)

though it's not mine, and it doesn't use stdin as input! but this is one of the best ones out there! it's a chess game with AI which can beat average human level just in 1023 bytes!

Can we assume we're not in check (without testing for that)? And don't have to test whether a move would uncover check?

@smci No, these assumes are not acceptable.

If you give the move in a standard format like FEN, you have the en passant target encoded, as well as castling availability. The only thing it can't do is a draw if the same position is seen 3 times. You need full history for that.

@CMP, a triple repetition is irrelevant here, because it's legal to do the move that leads to it, and also legal to ignore it and keep playing (it's a draw only if a player calls it).

I'm not complaining about upvotes, but to be fair... my solution here isn't actually all that great. Ugoren's is better, apart from lacking unicode support. Be sure to look at all the answers before voting, if you've come across this question only now!Anyway.
Haskell, 1074 bytes (without castling)
χ=w⋈b;w="♙♢♤♔♕♖♗♘";b="♟♦♠♚♛♜♝♞"
μ=t⤀ζ++((\(x,y)->(x,-y))⤀)⤀μ;q c|((_,m):_)<-((==c).fst)☂(χ⋎μ)=m
t(x:y:l)=(d x,d y):t l;t _=[];d c=fromEnum c-78
ζ=["NM","NL","MMOM","MMMNMONMNOOMONOO",σ⋈δ,σ,δ,"MLOLPMPOOPMPLOLM"]
σ=l>>=(\c->'N':c:c:"N");δ=[l⋎l,reverse l⋎l]>>=(>>=(\(l,r)->[l,r]))
l="GHIJKLMOPQRSTU"
α c|c∊"♢♤"='♙'|c∊"♦♠"='♟'|c∊χ=c;π('♙':_)=6;π _=1
(⋎)=zip;(⤀)=map;(∊)=elem;(✄)=splitAt;(☂)=filter;(⋈)=(++)
φ r@(x,y)p a
 |x>7=φ(0,y+1)p a
 |y>7=[]
 |c<-a✠r=(c⌥r)p a y⋈φ(x+1,y)p a
(c⌥r)p a y
 |c==p!!0=(a☈r)c χ++const(y==π p)☂(a☈r)(p!!1)χ++(a☈r)(p!!2)('…':w)
 |c∊p=(a☈r)c χ
 |True=[]
a✠(x,y)=a!!y!!(x*2);o(x,y)=x>=0&&x<8&&y>=0&&y<8
(n➴a)(x,y)|(u,m:d)<-y✄a,(l,_:r)<-(x*2)✄m=u⋈(l⋈(n:r):d)
(a☈r@(x,y))c b=(α c➴('…'➴a)r)⤀((\r->o r&&not((a✠r)∊b))☂((\(ξ,υ)->(x+ξ,y+υ))⤀q c))
main=interact$unlines.uncurry((⋈).zipWith((⋈).(:" ║"))['8','7'..]
 .head.((all(any('♔'∊)).φ(0,0)b)☂).φ(0,0)w.(drop 3⤀)).(8✄).lines

Try it online!

When you have GHC installed (for instance as part of the Haskell platform) you can do just
$ runhaskell def0.hs < examplechessboard.txt
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… ♘ … … ♟ … … …
4 ║… … … … … … … …
3 ║… … … … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

Now this is crazy :) I will check it out :)

Any idea how to test this awesomeness? Ideone.com can not handle it...

@HristoHristov: strange it doesn't work on Ideone. Probably has to do with the non-ASCII characters.

yes, this is the problem with ideone

Your example does not show a valid move, or do I miss something?

@HristoHristov: right, I messed up the order of the list ζ when I added double pawn starting-moves. Fixed now.

@leftaroundabout it's probably not about non-ASCII because it's created by Poles and all page must be in UTF-8 (i.e. "Zażółć gęślą jaźń").

This is mad.  I may have to learn Haskell.

@Hauleth I don't know... UTF-8 is just right for GHC, so I would have though it should work, but as soon as I put any non-ASCII characters into a program (as a variable name or string literal doesn't seem to matter) it refuses to compile. — Codepad appears to be somewhat more tolerant, but it doesn't work there, either.

@leftroundabout: Ideone uses GHC 6.8, which is quite old. It should work with a 7.x version.

Congratulations, you've managed to make Haskell look like APL. :-)

C, 734 672 640 characters
Characters counted without removable whitespace.
The file format I used is not as requested, but simplified ASCII.
I need to add Unicode character support, it would cost some characets.
char*r=" kpnbrq  KPNBRQ $ ,&)$wxy()879()8(6:GI(",B[256],*b=B,i;
e(x,d,m,V,c,r,n,p){
    for(r=0,p=b[x];m/++r;){
        n=x+d*r;
        if(p==2+8*(d<0)||n&136||!(b[n]?r=8,8^p^b[n]^8&&c&65^64:c&65^65)
            ? r=m,0
            : V?v(n,x):b[n]==1)
            return b[x]=0,b[n]=p%8-2||n/16%7?p:p+4;
    }
    return d>0&&e(x,-d,m,V,c);
}
d(x,v,m,i)char*m;{
    return(i=*m-40)?e(x,i%64,b[x]%8-2?b[x]&4?7:1:(x/16-1)%5|i%2?1:2,v,i)||d(x,v,m+1):0;
}
v(t,f){
    bcopy(B,b+=128,128);
    b[t]=b[f];b[f]=0;
    i=a(1,63);
    b=B;
    return!i;
}
a(c,n){
    return b[i=n*2-n%8]&&b[i]/8==c&&d(i,!c,r+r[b[i]%8+15]-10)||n--&&a(c,n);
}
main(){
    for(;gets(b);b+=8)for(;*b;b++)*b=strchr(r,*b)-r;b=B;
    for(i=64*!a(0,63);i<64;i++%8-7||puts(""))putchar(r[b[i*2-i%8]]);
}

Input/output file format:
Must be exactly 8 lines of exactly 8 characters. pnbrqk are used for white pieces, PNBRQK for black pieces, spaces for spaces:
RNBQKBNR
PPPP PPP

 n  P

pppppppp
r bqkbnr

The logic is quite simple:
For each possible move of each white piece, try each possible move of each black piece.
If no black move captures the white king, the white move is valid.
The board is maintained as char[256], treated as a 16x16 matrix, where only the top-left 8x8 is used. Positions and movement vectors are kept in 8-bit integers (x:4,y:4). The extra bit allows using simple arithmetic (new_pos = old_pos + steps*direction), with easy detection of the board edge (&0x88 does the magic).
r[] encodes three things:

The first 15 bytes map internal piece codes (K=1,P=2,N=3,B=4,R=5,Q=6) to letters.
The next 6 bytes map internal piece codes to offsets in the last part (K and Q are the same, B is their tail).
The last 16 bytes encode the movement of all pieces, as '('+vector.

Functions:

main reads the board, converts letters to internal code, calls a to find white moves, prints the board.
arecursively loops over the 64 squares. For each piece of the right color (parameter c), it finds the movement rule for the piece and calls d.
d recursively loops over the encoded movement rule, which is a list of vectors, calling e for each one. It gives e the original position, the vector and the range limit (7 for pieces above B, 2 for second rank pawns, 1 otherwise).
e tests all movements along a vector. If the move is possible (i.e. pawns move forward, within board, not blocked, pawn capture diagonally), checks one of two things. For white moves, runs v to validate the move. For black moves, checks if the white king is captured. If true, the move is played on the board.
v validates a white move. It copies the board aside, executes the move to test, and calls a again, to look for black moves.

At last, a solution with proper compressed encoding of the possible moves! And it's nicely fast. Don't you think you could add a Unicode wrapper and still be shorter than my code?

@leftaroundabout, I guess I can. The main problem is that I'm working in a Linux command line, where you can't see Unicode, so debugging it would be annoying. I also have a version that saves about 40 more bytes (I'll update soon), so I have lots of chars to work with.

@ugoren: Surely any half-way modern Linux distribution supports UTF-8 out of the box?

@han, I'm working on Windows and connect to Linux by SSH, and Unicode doesn't work. I can write to a file and open in in Windows, but it just isn't interesting any more.

Will this compile with gcc? I'm using Geany for Windows with MinGW and it will compile with a bunch of errors and warnings but it will not build/run.eg:C:\Users\xxx\AppData\Local\Temp\ccpBG9zy.o:codegolfchess.c:(.text+0x2d8): undefined reference to `bcopy'                                                      collect2: ld returned 1 exit status

@rpd, It's meant for gcc/Linux. Try replacing bcopy(x,y,l) with memcpy(y,x,l).

Python 2.6, 886 - 1425 characters
My initial version (in the revisions) came in at 886 characters but did not satisfy the spec completely (it did not check for avoiding checkmate ; it didn't even consider the possible moves of the black pieces).
Now it does (and I've fixed several bugs in the original). Alas this comes with a cost in characters: 1425 for now, but there should still be little room for improvement. This version should be a lot more solid in handling edge cases then the previous one.
#-*-coding:utf8-*-
import sys;e=enumerate
B,W=["♟","♜","♞","♝","♛","♚"],["♙","♖","♘","♗","♕","♔"]
R={"♙":[11,42],"♖":[28],"♘":[31],"♗":[8],"♕":[8,28],"♔":[1,21]}
def F(w):return sum([[(i,j)for j,p in e(o)if p==w]for i,o in e(Z)],[])
def G(x,y):
 P=Z[x][y];D=P in W;L=[]
 for o in R[P]if D else R[unichr(ord(P.decode('utf8'))-6).encode('utf8')]:
  r,k="%02d"%o
  for g,h in[[(-1,-1),(1,1),(-1,1),(1,-1)],[[(1,-1),(1,1)],[(-1,-1),(-1,1)]][D],[(-1,0),(1,0),(0,-1),(0,1)],[(-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1)],[(-1,0)]][int(r)]:
   J=0
   for i in range(int(k)):
    T=x+(i+1)*g;U=y+(i+1)*h
    if T<0 or T>7 or U<0 or U>7:break
    M=Z[T][U]
    if not J:L.append((T,U,P,M))
    else:break
    if r in"02"and(M in W+B):
     J=1
     if not((D and M in B)or(not D and M in W)):L.pop()
    elif(r=="1"and not((D and M in B)or(not D and M in W)))or(r=="4"and((i==1 and x!=6)or M!="…")):L.pop()
 return L
Z=[[y for y in l[5:].split()]for l in sys.stdin.readlines()[:-2]]
Q=[]
for p in R:
 for i,j in F(p):
  for M,L,c,_ in G(i,j):
   O=Z[M][L];Z[i][j]="…";Z[M][L]=c;E=[];map(E.extend,map(F,B))
   if not any(any(1 for _,_,_,I in G(v,h)if I==["♔","♚"][c in B])for v,h in E):Q.append((i,j,M,L,c))
   Z[i][j]=c;Z[M][L]=O
(x,y,X,Y,p)=Q[0];Z[x][y]="…";Z[X][Y]=p
for i,h in e(Z):print`8-i`+' ║'+' '.join(h)
print"——╚"+"═"*16+"\n—— a b c d e f g h"

Example input and output:

# INPUT

8 ║♜ ♞ ♝ … ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … ♙ ♛
3 ║… … … … … ♙ … …
2 ║♙ ♙ ♙ ♙ ♙ … ♙ …
1 ║♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

# OUTPUT

8 ║♜ ♞ ♝ … ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … ♙ ♛
3 ║… … … … … ♙ ♙ …
2 ║♙ ♙ ♙ ♙ ♙ … … …
1 ║♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
——╚════════════════
—— a b c d e f g h

It's 886 bytes, but only 854 chars. (My program has over 1kB, thanks to the many non-ASCII operators!) — Are you going to add checking for taking the king yet?

@leftaroundabout: I've added the king checks (which forces me to also account for possible moves of black, and adds a lot of characters...). Oh well, this version should be more solid around edge cases (as far as I tested).


text:
String manipulation
The challenge is to manipulate strings using basic Vim-like commands
Input:

A string of text to be transformed. The input alphabet is [a-z].
A string of legal commands

Output:

The transformed string

There are a few ideas you should understand:
The cursor is represented as a location between 2 characters. | will be used to represent the cursor(s) in this explanation.

|foobar - The cursor at beginning of string
foo|bar - Cursor in the middle of the string
foobar| - Cursor at the end of the string

A selection is a a group of characters between 2 cursors.

|foobar| - The selection is foobar
|foo|bar - The selection is foo
foo|bar| - the selection is bar
|foobar  - The selection is the empy string (both cursors at same location)

A selection is formed from the previous cursor position and the result of the current command.
Using the command > on |foo would make the selection |f|oo.
Commands can be described as functions. C<selection> is a command that has a selection parameter. The next command provides the selection.

D> deletes the character to the right of the cursor. f|oo -> f|o
DNa deletes from the cursor to the next a character f|oobar -> f|ar
Etc.

As you can see, commands "associate to the right"

DNa is parsed as (D(Na))
DDNa is parsed as (D(D(Na)))
Etc.

The insert mode command I extends until the next command.

DIbar> is parsed as (D(Ibar))(>).

These are the commands:

> - Move cursor right. > on foo|bar -> foob|ar
< - Move cursor left. < on foo|bar -> fo|obar
B - Move cursor to the beginning of the string
E - Move cursor to the end of the string
N<char> - Move cursor to place before next <char>. Na on |foobar -> foob|ar
P<char> - Move cursor to place after previous <char>.  Po on foobar| -> foo|bar
I<string> - Enter/exit insert mode. Characters in <string> are inserted at the current cursor position. <string> extends until the next command.
The cursor is moved to end of insertion <string>. Iquz on foo|bar -> fooquz|bar
D<selection> - delete characters in <selection>. f|ooba|r -> f|r. The output selection from this command is the empty string.

Notes:

The cursor cannot move out of bounds. B<<< is the same as B. Nx is the same as E if no x can be found.
The cursor location always starts at the beginning of the string
The cursor should not be outputted
Commands are always uppercase, characters are lowercase.

Restrictions:

No text editor scripts like Vimscript

Winning criteria:

It's code golf. Lowest character count wins.

Examples:
Input:

foobar
>>><<>If

Output:

fofobar

Input:

foobar
>>>DNEDPf

Output:

f

Input:

foobar
>>>DDDDIbazD<Iquz>DPfDII

Output:

far

"<string> extends until the next command."
But how do we know that it's a command rather than part of the string?

@PeterTaylor Commands are uppercase, characters are lower.

I'm starting to think that this question might be a bit too complicated for a code-golf tag.

The first example is like teaching a 4th grader how to multiply; the second example is like trying to teach that 4th grader algebra, and the third example is like trying to teach that 4th grader calculus.

Haskell, 371 characters
z l b n i=p where
 p(a:c@ ~(q:u))|Just x<-a`lookup`zip"<>BEDNP"[l#c,m l#c,b#c,m b#c,z(d$k id)(\k _->k"")h(k f)c,m(n q)#u,n q#u]=x
 p('I':q:c)|q>'`'=i q c;p(_:c)=f c;p""=(++).r
d f k(q:x)=k x.f q;d f k""=k"";k&x=k"".(r x++);h q=(.snd.s q);n q k=(\(a,b)->k b.(r a++)).s q
x%c=f c""x;f=z(d(:))(&)n$ \q c->f('I':c).(q:);m f=flip.f.flip;k=const;r=reverse;(#)=(.f);s=span.(/=)

This defines a function % which returns the result of applying the string of commands to the original string.
Example usage:
> "foobar" % ">>>DNEDPf"
"f"
> "foobar" % ">>>DDDDIbazD<Iquz>DPfDII"
"far"