text:
Implement arbitrary precision division
Implement a function divide(int a, int b, int c) that prints the base 10 value of a/b. without using any floating point math nor BigInteger/BigDecimal or equivalent libraries whatsoever. At least c accurate characters within the set of 0123456789. must be printed, except for the (possible) exception in point 4 below.

a and b may be any 32 bit integers. Update: If, for golfing purposes, you would like to have input be 64 bit primitives that is okay, but you do not need to support the whole 64 bit range of data.
You do not need to check that c is positive (though hopefully your program does not crash) if it's not.
The minimum supported upper bound for c is 500. It is okay if your program does not support values of c above 500, but it is also okay if it does.
For numbers that divide evenly, it is your choice whether to print extra zeroes (based on the value of c) or nothing.
You do not need to be able to use the function to do any further tasks with the quotient, the only goal is printing.
For numbers between -1 and 1, it is your choice whether to print a leading 0. However, this is the only scenario where printing a leading zero is acceptable, and you may only print one such zero.
You may use any rounding / floor / ceil logic you prefer for the last decimal place.
For a negative answer, you must print a leading -. This does not count towards c. However, it is your choice if you wish to print  , +, or nothing for a positive answer.
Integer division and integer modulus are both allowed. However, keep in mind that you are restricted to primitives, unless you choose to implement your own BigInteger/BigDecimal library which counts against your code length.
You do not need to handle b being 0, though you can if you want. Your program may enter an infinite loop, or crash, if b=0, and you will not be penalized.
Slight rule change per comment. To make sure the playing field is level, while a and b are guaranteed to be 32 bit integers, you may use 64 bit long integers. If your chosen language goes beyond 64 bit integers as a primitive, you may not at any point use that functionality (pretend it is capped at 64 bits).
Another point that is unclear (it shouldn't change any of the current valid answers, though): while c may be interpreted as either the number of printed characters or the number of spaces after the decimal, your program must use c somehow in a relevant way to decide how many characters to print. In other words, divide(2,3,2) should be much shorter output than divide(2,3,500); it is not okay to print 500 characters without regard to c.
I actually don't care about the name of the function. d is okay for golfing purposes.

Input
Both a function call and reading from stdin are accepted. If you read from stdin, any character not in the set [-0123456789] is considered an argument delimiter.
Output
Characters to stdout as described above.
Example
for divide(2,3,5), all of the following are acceptable outputs:
0.666
0.667
.6666
.6667
 0.666
 0.667
 .6666
 .6667
+0.666
+0.667
+.6666
+.6667

Another example: for divide(371,3,5) the following are all acceptable outputs:
123.6
123.7
 123.6
 123.7
+123.6
+123.7
123.66666
123.66667
 123.66666
 123.66667
+123.66666
+123.66667

And for divide(371,-3,5) the following are are all acceptable:
-123.6
-123.7
-123.66666
-123.66667

For the sake of a level playing field, it might be wise to give a specific maximum bit length that can be used (primitive or otherwise) unless you roll your own larger implementation, because a) in some languages bit length of primitives varies depending on the underlying architecture and b) in some languages big number types are primitives.

@JonathanVanMatre Added rule 11 per your comment

How do you count accurate digits? In your example I see three or four but never five as the last argument indicates.

@Howard, if you did 92,3,5 the answer would be, for example, 30.67

btw 370/3=123.333 lol

@izabera boy am I tired lol

I think this title is misleading. "Arbitrary precision division" usually means "can divide arbitrarily large integers". This is not that. I see where it comes from, displaying an "arbitrary" number of decimal places, but I believe that the title would be better if it was changed.

Java, 92/128
void d(long a,int b,int c){if(a<0^b<0){a=-a;p('-');}for(p(a/b+".");c>0;c--)p((a=a%b*10)/b);}<T>void p(T x){System.out.print(x);}

I had to improvise so that a or b could be -2147483648 as positive 32-bit integers only count towards 2147483647, that's why a became a long. There could be a better way of handling negative results, but I know none (doubles would probably get this to work for abs(a) < abs(b) as they have -0 but only ones' complement would keep the precision).
Why two byte numbers? I needed 92 bytes for the calculation and 36 for the print-helper (System.out.print sucks; generally Java isn't that golfy).
public class Div {

    void d(long a, int b, int c) {
        if (a < 0 ^ b < 0) {
            a = -a;
            p('-');
        }
        for (p(a / b + "."); c > 0; c--) {
            p((a = a % b * 10) / b);
        }
    }

    <T> void p(T x) {
        System.out.print(x);
    }

    public static void main(String[] args) {
        final Div div = new Div();
        div.d(12345, 234, 20);
        div.p('\n');
        div.d(-12345, 234, 20);
        div.p('\n');
        div.d(234, 234, 20);
        div.p('\n');
        div.d(-234, 234, 20);
        div.p('\n');
        div.d(234, 12345, 20);
        div.p('\n');
        div.d(234, -12345, 20);
        div.p('\n');
        div.d(-234, 12345, 20);
        div.p('\n');
        div.d(-234, -12345, 20);
        div.p('\n');
        div.d(-2147483648, 2147483647, 20);
        div.p('\n');
        div.d(2147483647, -2147483648, 20);
        div.p('\n');
    }
}

The method basically exercises what most of us learned at school to generate the requested decimal digits.

Official ruling: I would say that ignoring Integer.MIN_VALUE is not okay but that long as input is fine.

That's a lot shorter. Nicely done.

@durron597 thank you. Still the strict typing and System.out make Java feel bulky ;-) Still a good feeling, that there already are longer answers posted.

I just added rule 13 for you. By the way, I don't know what's normal for golfing in Java, is public class D{} normally counted against your total?

@durron597 you specifically asked for a function so I tought it would not count. If I had to use imports than probably yes.

I suppose if public class and public static void main counted against Java programs the language would be totally thrown out for golfing, haha

At least there is no $ to every variable ;-)

C, 98 95 89
d(a,b,c){if(a>0^b>0)a=-a,printf("-");for(printf("%d.",a/b);c--;putchar(a/b+48))a=a%b*10;}

prints c digits after the .
example output:
d(2,3,5);
0.66666

d(-2,3,5);
-0.66666

d(24352345,31412,500);
775.25611231376543995925124156373360499172290844263338851394371577740990704189481726728638736788488475741754743410161721635043932255189099707118298739335285878008404431427479943970457150133706863618999108620909206672609193938622182605373742518782630841716541449127721889723672481854068508850120972876607665860180822615560932127849229593785814338469374761237743537501591748376416656055010823888959633261174073602444925506175983700496625493441996689163377053355405577486310963962816757926906914554947153953

d(-77,12346463,500);
-0.00000623660395693892250760399962321192717298873369644407471192356871761572524859953818352673150196943043525906974329409159530142357369879940514137530724386409289850866600418273638369142644334656816288195250736992448768525852302801215214430238036593962173620088603513411087855687900251270343579371679160258286118056645048869461642577311412993340683886551152342172814999729072204727783171585254821563066280601982932277851559592411203111368818745903178910429650985873444078680671541315111866451144752954

should work for -2147483647<=a<=2147483647, same for b. handling the - was a pain.
online version: ideone

Does this work for a being -2147483648? Don't know c compilers well enough to tell which integer-type is assigned to your parameters.

thanks for pointing it out. it works correctly for -2147483647<=a<=2147483647, same for b. there's a problem when a=-2147483648 and b is positive due to a=-a.

I tried but eventually got essentially the same solution as you. You can save one character by realizing that printf("-") returns 1.

PHP, 108
function d($a,$b,$c){$a*$b<0&&$a*=-print'-';for($p='.';$c--;$a.=0,print$i.$p,$p='')$a-=$b*$i=($a-$a%$b)/$b;}

It works by simply outputting the quotient of a / b during a loop of c steps, a becoming the remainder multiplied by 10 at each iteration.
DEMO

Produces strange results when a or b are negative

I fixed the bug for negative numbers. Thanks!

Just found a 112 version of your code: function d($a,$b,$c){if($a*$b<0)$a*=-print'-';for($p='.';$c--;$a*=10,$p=''){$a-=$b*$i=($a-$a%$b)/$b;echo$i.$p;}} see return value

Thanks. I even updated your version and managed to win an extra 1 byte.

Python 111
f=lambda a,b,c:'-'[a*b>=0:]+'%s'%reduce(lambda(d,r),c:(d%c*10,r+`d/c`+'.'[r!='':],),[abs(b)]*c,(abs(a),''))[-1]

This solution does not violates any of the stated rules.

You can save 2 bytes by deleting f=

C: 72 characters
d(a,b,c){for(printf("%d.",a/b);c--;putchar((a=abs(a)%b*10)/abs(b)+48));}

It almost entirely does what it is supposed to do. However it will as some of the other answers here give wonky values or fail for d(-2147483648,b,c) and d(a,-2147483648,c) since the absolute value of -2147483648 is out of bounds for a 32-bit word.

Perl, no arithmetic, 274 bytes
This is Euclidean long division, likely to consume an unusual amount of memory.  The closest it gets to math on floating-point numbers is in using bit operations to parse them.
sub di{($v,$i,$d,$e)=(0,@_);($s,$c,$j)=$i=~s/-//g;$s^=$d=~s/-//g;
$i=~s/\.(\d+)/$j=$1,""/e;$d=~s/\.(\d+)/$c=$1,""/e;
$z=0.x+length($c|$j);$i.=$j|$z;$d.=$c|$z;
($e,$m,$z,$t)=(1.x$e,0.x$i,0.x$d,"-"x($s&1));
for(;$e;$t.="."x!$v,$v=chop$e){$t.=$m=~s/$z//g||0;$m="$m"x10}
print"$t\n"}

Examples:
di(-355,113,238);
di(1.13,355,239);
di(27942,19175,239);
di(1,-90.09,238);
di("--10.0","----9.801",239);
di(".01",".200",239);

Output:
-3.141592920353982300884955752212389380530973451327433628318
584070796460176991150442477876106194690265486725663716814159
292035398230088495575221238938053097345132743362831858407079
646017699115044247787610619469026548672566371681415929203539

0.0031830985915492957746478873239436619718309859154929577464
788732394366197183098591549295774647887323943661971830985915
492957746478873239436619718309859154929577464788732394366197
183098591549295774647887323943661971830985915492957746478873

1.4572099087353324641460234680573663624511082138200782268578
878748370273794002607561929595827900912646675358539765319426
336375488917861799217731421121251629726205997392438070404172
099087353324641460234680573663624511082138200782268578878748

-0.011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011

1.0203040506070809101112131415161718192021222324252627282930
313233343536373839404142434445464748495051525354555657585960
616263646566676869707172737475767778798081828384858687888990
919293949596979900010203040506070809101112131415161718192021

0.0500000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000

Ruby, 178
def d(a,b,c)
    n=(a<0)^(b<0)
    a=-a if n
    m=a/b-b/a
    l=m.to_s.size-1
    g=(a*10**(10+c)/b).to_s
    f=m<0?"."+"0"*(l-1)+g[0..c-l-1] : g[0..l]+"."+g[l+1..c-2]
    p n ? "-"+f : f
end

Online version for testing.
The trick is to multiply a with a pretty high number, so the result is just an integer multiple of the floating point operation. Then the point and the zeros have to be inserted at the right place in the resulting string.

Does this work for c bigger than 350?

I tested it with c=1000 - the code gave me an answer, maybe I should check the actual result though...

does g get beyond 64 bits for large c? Edit: I think you are implicitly using BigInteger here

Err, g is a string, but before you call to_s you've created a number in memory that is beyond 64 bits in size

Well, the new rule #11 might just forbid this answer - it's new, isn't it? ;)

It is new, yes, but I was trying to forbid it in the original question when I talked about BigInteger etc. Rule 11 is more of a clarification of what I meant by that.

That is understandable - and makes the task more challenging (and interesting)! Is it better to delete the answer or leave it for others to have an example of how not to implement the task?

python 92 bytes:
def d(a,b,c):c-=len(str(a/b))+1;e=10**c;a*=e;a/=b;a=str(a);x=len(a)-c;return a[:x]+'.'+a[x:]

i think some more golfing is possible.....

does e get beyond 64 bits for large c? Edit: I think you are implicitly using BigInteger here.

@durron597 i highly doubt that. It goes to BigInt(Long in python) but 2**45 is 48 bits. Is that enough presicion?? Also, python has NO primitives so...

If a=5 and c=400 then after e=10**c, in hex, the number is 333 digits long. It starts 8889e7dd7f43fc2f7900bc2eac756d1c4927a5b8e56bbcfc97d39bac6936e648180f47d1396bc905a47cc481617c7... this is more than 64 bits.

@durron597 400... do i need that

Yes rule 3 says you need to support up to at least 500... I was trying to prevent this (imo trivial) solution.

oh oops... sorry

C 83
d(a,b,c){printf("%d.",a/b);for(a=abs(a),b=abs(b);c--&&(a=a%b*10);)putchar(a/b+48);}

Same Idea that I used in my python implementation

Very nice! However, it crashes on d(-2147483648,-1,10)

source: Stack Exchange

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

sort: votes


text:
Create an n to the d tic tac toe win-checker
Create the shortest program to check who has won in an nd tic tac toe game.
Your program should work when n (width) and d (dimension number) are in these ranges:
n∈[3,6]∩ℕ  ie a number from this list: 3,4,5,6
d∈[2,5]∩ℕ  ie a number from this list: 2,3,4,5

n = 3; d = 2 (32 ie 3 by 3):
[][][]
[][][]
[][][]

n = 3; d = 3 (33 ie 3 by 3 by 3):
[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

n = 6; d = 2 (62 ie 6 by 6):
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]

And so on.
Winning (If you've played enough multi-dimensional tic tac toe, this is the same.)
In order for there to be a win, one player must have all the adjacent squares along a line. That is, that player must have n moves on a line to be a winner.
Adjacent:

each tile is a point; for example (0,0,0,0,0) is a point in d=5
adjacent tiles are tiles such they are both points on the same unit d-cube. In other words, the Chebyshev distance between the tiles is 1.
in other words, if a point p is adjacent to a point q, then every coordinate in ps corresponding coordinate in q differs from it by no more than one. Additionally, at least on coordinate pair differs by exactly one.

Lines:

Lines are defined by vectors and a tile. A line is each tile hit by the equation: p0 + t<some vector with the same number of coordinates as p0>

Input:
Input will be to STDIN. The first line of input will be two numbers, n and d in the form n,d.
After this will be a line consisting of coordinates specifying the moves that have been done. Coordinates will be listed in the form: 1,1;2,2;3,3. The upper left corner is the origin ( 0,0 for 2D). In the general case, this list will be like 1,2,...,1,4;4,0,...,6,0;... where the first number represents left-right-ness, the second up-down-ness, the third through the 3rd dimension, etc. Note that the first coordinate is Xs first turn, the second is Os first turn, ....
The input will be followed by a newline.
Output:
Output will be to STDOUT. Simply indicate who won if someone won, or if it is a tie. If it is neither a tie nor a win, don't output anything.
Additionally, indicate if there is a move clash, that is, if there are at least two moves in the same location.
If there was a win/draw before the input ended, your program can do whatever it wants.
Test cases (anyone want to suggest any more?):
Input:
4,3
0,0,0;1,1,1;1,0,1;2,0,2;0,0,1;2,0,0;2,0,1;3,0,2;3,0,1

Example Output:
X wins

Another possible output (requires explanation):
1

How are you defining the topology of dimensions n>3 for determining what a straight lines along a diagonal is? For example, does any line through any 3 adjacent vertices constitute a win on a 3⁵ board? Are the middle squares of each 3² plane connected to every point of another plane that shares an edge with it on the n-cube?

@Comintern How's that (I probably butchered the explanation. Could definitely be simpler).

Note: the definitions you gave for adjacent tiles are not equivalent (i.e. it is not manhattan distance equals one).

Moreover you should define that it takes n moves on a line to be a winner. (Sorry for not posting these remarks in the sandbox but I didn't even have time to even see it there because it was posted so soon after sandboxing.)

@Howard Ugh. I'm so confused. What do you call distance when traveling diagonally across a unit-right triangle is the same distance as traveling across the leg?

I'm no mathematician - maybe maximum metric?

@Howard Got it. The two points are both on the same unit cube.

That makes a lot more sense now. I was envisioning more as rotating the 3D board 90° through 4D and 5D space.

I feel like there should be a very short solution in Prolog...

Definition of line is unclear to me. Does right-right-up&right-right count? I think current def. might allow for that as well..

Python, 745 578 Characters
import sys
x=[]
o=[]
t=1
b=","
k=map
def m(c):
 m=x if t else o
 c=k(int,c.split(b))
 if c in o+x:
  print b
  sys.exit()
 m.append(c)
 r=0
 for p in m:
  r=w(p,m)
 return r
def w(p,m):
 for q in m:
  d=max(k(lambda x,y:abs(x-y),p,q))
  if d==u:
   if e(p,q,m):
    return 1
 return 0
def e(p,q,m):
 v=k(lambda p,q:(p-q)/u,q,p)
 l=p
 for i in range(1,n):
  y=k(lambda j,h:j+h,l,v)
  if y not in m:
   return 0
  l=y
 if not l==q:
  return 0
 return 1
q=sys.stdin.readline
d=q()
v=q()
z=d.split(b)
(n,d)=k(int,z)
a=v.split(";")
u=n-1
for c in a:
 r=m(c)
 if r:
  print t
 t=not t

I made some changes and shrank it down quite a bit. Note that a return of True means that x has won, False means y won, and , means that an invalid move was made.

Some things: change import * to import*. Use 1 for True, and 0 for False (remove T and F). return -1 can be return-1 (check out removing spaces). Rename your methods into single char methods. Check out [tag:tips] for more optimizations.

Oh, thanks, I didn't know you could do some of those things (namely, remove the space between return and -1)

I did a little bit of golfing on your code (that may not all be valid). The result is here: http://ideone.com/Ld2jAH . Please go through your answer again and shorten the code as much as you can. The [tag:tips] question for python is very useful

@foota You can do if l<>q: instead of if not l==q:.

Not an answer - Java
I was curious to see how many different ways there were to win for a given n,d so I wrote this code to list them all.
import java.util.*;

public class MultiDTTT {
    static Set<Win> wins = new HashSet<Win>();
    static final int d = 3;
    static final int n = 3;
    static final char maxChar = (char)(n-1) + '0';

    public static void main(String[] args) throws Exception {
        String pad = "";
        for(int i=0; i<d; i++) pad = pad + "0";
        for(int i=0; i<Math.pow(n,d); i++) {
            String s = Integer.toString(i,n);
            s = pad.substring(s.length()) + s;
            buildWin(s,"",0);
        }
        System.out.println(wins.size());
        for(Win w : wins) System.out.println(w.toString());
    }

    static void buildWin(String s, String p,int i) {
        if(i<d) {
            if(s.charAt(i) == '0') {
                buildWin(s,p+"u",i+1);
                buildWin(s,p+"s",i+1);
            }
            else if(s.charAt(i) == maxChar) {
                buildWin(s,p+"d",i+1);
                buildWin(s,p+"s",i+1);
            }
            else {
                buildWin(s,p+"s",i+1);
            }
        }
        else {
            if(p.contains("u") || p.contains("d")) wins.add(new Win(s,p));
        }
    }

    static class Win {
        String start;
        String pattern;
        Set<String> list = new HashSet<String>();

        Win(String s, String p) {
            start = s;
            pattern = p;
            char[] sc = s.toCharArray();
            for(int i=0; i<n; i++) {
                list.add(new String(sc));
                for(int j=0; j<d; j++) {
                    switch (p.charAt(j)) {
                        case 'u':
                            sc[j]++;
                            break;
                        case 'd':
                            sc[j]--;
                            break;
                        case 's':
                            break;
                    }
                }
            }
        }

        public String toString() {
            String s = ""; //start + ", " + pattern + "\n    ";
            for(String ss : list) s = s + ss + " ";
            return s;
        }

        public boolean equals(Object x) {
            return (x instanceof Win) && this.list.equals(((Win)x).list);
        }
        public int hashCode(){
            return list.hashCode();
        }
    }
}

I hand-tested it on n,d = 2..3,2..3 and it appears to work… after that the number of possible ways to win grows quickly as shown below:
n       1       2       3       4       5       6
d
1       1       1       1       1       1       1
2       1       6       8       10      12      14
3       1       28      49      76      109     148
4       1       120     272     520     888     1400
5       1       496     1441    3376    6841    12496
6       1       2016    7448    21280   51012   107744

Having generated all wining sets, I could extend the program to check the given input against winning sets but, of course, that method would never win the golf.  So I was content to stop here - except it looked like I could find a closed-form solution for the number of ways to win as a function of n and d… It is Number of ways to win = 0.5( (n+2)^d - n^d).

C++ 794 849 chars
#include <algorithm>
#include <iostream>
#include <cmath>
#include <string>
#define _ return
#define Y int
#define Z(a) cout<<#a
#define W(a,b,c) for(a=c;a++<b;)
using namespace std;Y n,d,A[5],P[6],T=1,x[7776]={},i,j,k,a,z,p=pow(n,d);char c;bool B;string s;Y K(){a=P[j];W(k,i,0)a/=n;_ a%n;}Y M(){j=0;z=K();W(j,n,1){if(K()!=z){_ 1;}}_ 0;}Y N(){W(j,n,0)if(K()!=n-1-j)_ 1;_ 0;}Y O(){W(j,n,0)if(K()!=j)_ 1;_ 0;}Y S(){z=0;W(i,d,0){z*=n;z+=A[i];}_ z;}Y C(){a=z=0;W(i,p,0){if(s[i]-'0'){P[z]=i;++z;if(a){if(x[i]!=a)_ 0;}else a=x[i];}}_ a;}Y L(){W(i,d,0)if(M()*N()*O())_ 0;_ 1;}Y main(){cin>>n>>c>>d;while(1){W(i,d,0)B=cin>>A[i]>>c;if(x[S()]){Z(!);_ 0;}x[S()]=T;T*=-1;if(!B)break;}W(i,p,0)i<n?s+="1":s+="0";do if(C()&&L()){C()==1?Z(X):Z(O);_ 0;}while(prev_permutation(s.begin(),s.end()));_ 0;}

Output is: "X" (X wins), "O" (O wins), or "!" (illegal move attempt).
This just maps the points into a linear array and checks all possible subsets of size n, first for being constant at X or O, and then for being in a line. To check for being in a line, the coordinates of the points in each subset are examined one at a time; they must each be either increasing from 0 to n-1, decreasing from n-1 to 0, or constant. The points are naturally ordered in the linear array, so it makes sense to call a coordinate increasing or decreasing for a given set of points.
Thanks to Howard for pointing out a serious mistake in the first version.
In solidarity with Quincunx, I have to point out that it would be a travesty if a C++ answer wins

I think that while you can say that being in line implies arithmetic progression, it does not hold the other way round (e.g. 0,2,4 won't be a solution for the standard 3,2 tic tac toe).

@Howard, thanks. I've made the corrections. It's too late now for me to finish golfing it, but I was able to fix it (I think).

You can golf it further by using different outputs. You don't have to say exactly X wins or O wins. It is perfectly legitimate to output 1 or 2 (or some other variation) as long as you explain in your answer what they stand for. As I said (emphasis added): "indicate who won".

Done. And if I can learn how the ternary operator works, I can save a few characters.

What about ties?

@EricTressler Ternary works as follows (if c++ syntax is the same as many syntax's, like Java's): condition ? this_if_true : this_if_false;. The condition is evaluated, and the code before the : is returned (by the expression) if it is true, otherwise the code after is returned.

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


text:
More coding expressions like while(!(succeed = try()))?
I am looking for either suggestions or examples of more famous sayings written in code! If you have a website or database of them, please link that below your favorite one!
Examples:
while(!(succeed = try()))

if(lifegivesyou == lemons) {makelemonade();)

I prefer if(life.gives(you,lemons)) you.throw(lemons,'people you don\'t like')

if (glass.getLevel() == 0.5)
    throw new ContainerTooLargeException(glass + " is twice as big as it needs to be.");

Wouldn't that be an OptimismException?

The optimist says the glass is half full. The pessimist says it's half empty. The engineer says the glass is twice as big as it needs to be.

How about:
~wish&~want;

or
Penny.Earned = Penny.Save();

Nice ones! I wish I could upvote! MOAR PLS

Shouldn't this just be
Penny saved = earned;

bash
say "It's going to be legen..."
waitforit
say "dary!"

C++
Toast toast = New Toast();
toast.fillside("butter", "up");
toast.fall(); //this method swaps sides, now buttered side is down


text:
Magrathea 2.0 - Building Mountains
With the big crash of the universal economy also the demand for custom made planets plunged. The Magratheans had to look after more steady revenues also from a broader class of customers. Therefore, they invented the have-your-own chain of mountain (or short havoc-o-mountains) for people with smaller budget who could not afford a complete planet.
The mountains are build according to the customer's plan (a.k.a. strings of digits and dots) and delivered using ascii-art (consisting of  , /, \, ^ and v).
Task
Write a complete program which takes input (single string) either from STDIN or as argument and outputs to STDOUT. This puzzle is a code-golf so please show some attempt at golfing.
Input
A string of dots and digits providing the basis for the mountain chain. Each string is exactly as long as necessary to support the mountains and each peak is given by a digit instead of a dot, indicating the height of the peak.
Output
An ascii version of the mountain chain.

Each digit in the input represents exactly one peak (^) at exactly the height indicated by the digit (i.e. 9 is the highest height).
There must not be additional peaks in the output (i.e. at places where there is a dot in the input).
Mountains are of triangular shape, i.e. slopes are created using / and \ characters.
Passes where two mountains overlap are shaped using the character v.
No superfluous newlines nor blank lines.
Padding lines with trailing spaces is optional.

You may assume that the input provided is valid, i.e. there always exists a solution according to the rules (e.g. an input of 13.. would not result in a valid configuration and may be ignored). Moreover, on each side there are exactly as many dots such that the mountains must no be cropped.
Examples
The first line shows the input, all other lines constitute the desired output. (Actually the mountains look much better in my console than here.)
1
^

11
^^

1.2.
  ^
^/ \

.2.3..
   ^
 ^/ \
/    \

.2..3..
    ^
 ^ / \
/ v   \

...4...3...3..
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \

What a combination of poetry and art!  I love it.

Is printing extra newlines okay? In other words, for an input of 1, is \n\n\n\n\n\n\n\n^ allowed?

@durron597 The output should have no superfluous newlines, have a look at the examples.

What about trailing space characters?  Is it OK if all lines are the same length as the original string, padded out with spaces?

@Chron Yes, that's OK.

Hmm, what would the result be for "..32."?  I suspect my code is handling this incorrectly, assuming it's a valid input.

Great question!
Note: running $('pre').css({lineHeight:'1em'}) on the browser's console will make the mountains look less like Christmas trees :)

Javascript: 272 268 233 232 201 192 189 188 178 180 characters
Thanks to @Sam for reducing it from 268 to 233 characters, and for @manatwork for another 1 char. @VadimR for pointing out a bug.
p=prompt(r=t='');s=' ';for(d=10;d--;r=s+q+s,t+=q.trim()?q+'\n':'')for(q='',i=0;i<p.length;)q+=' \\/v^'[p[i++]==d?4:(/\^|\\/.test(r[i-1])+2*/\^|\//.test(r[i+1]))*(r[i]==s)];alert(t)

Properly idented and somewhat ungolfed version with comments:
// The output initialization is just a golfing trick suggested by @manatwork.
input = prompt(state = output = '');
space = ' ';

// Repeat for each line, from the top (the highest peak, highest digit) to the floor (digit 1). Start at 10 to avoid a bug.
for (digit = 10; digit--;

      // Update the state of our automaton, at the end of the iteration.
      // Add a space after and before to simplify the future pattern recognization.
      state = space + line + space,

      // Add the line to the output if it is not an empty line, at the end of the iteration.
      output += line.trim() ? q + '\n' : '')
{ // This curly brace was added for readability, it is not in the golfed source.

  // Analyze each character in the current state to produce a new state, like a cellular automaton.
  for (line = '', i = 0; i < input.length;)
  { // This curly brace was added for readability, it is not in the golfed source.
    line +=

        // If the input is the current digit number, evaluate to 4 and put a peak in this character.
        // Otherwise evaluate this expression with those rules:
        // 1 means that the hill is higher only at right in the previous iteration, we do climb it to the right in this one.
        // 2 means that the hill is higher only at left in the previous iteration, we do climb it to the left in this one.
        // 3 means that the hill is higher at both sides in the previous iteration, we are in a v-shaped valley.
        // 0 means nothing to do here. If the middle is not a space, it will be multiplied by 0 and become 0.
        ' \\/v^'[input[i++] == digit ? 4 : (/\^|\\/.test(state[i - 1]) + 2 * /\^|\//.test(state[i + 1])) * (r[i] == space)];
    } // This curly brace was added for readability, it is not in the golfed source.
} // This curly brace was added for readability, it is not in the golfed source.

// Give the final output.
alert(output);

As you may note from the code, this works as a cellular automaton, where each cells checks for a number in the input, looks to itself and to its two neighbours to decide what the next iteration will be. At each moment a cell may be a ^, /, \, v or . The input provided in the test cases produces the expected output.
Note that using the alert box sucks, since it normally does not have a monospaced font. You may copy & paste the text from the alert box to somewhere else for a better appreciation of the output, or you may replace the last line alert by console.log, but since this is code-golf, alert is shorter.
Further, it does not validates anything in the input. It simply considers unrecognized characters as spaces the same way it does to . (in fact . is an unrecognized character too).

There is an old golfing trick to reduce 1 character: initialize variables with empty string as prompt()'s parameter.

Excuse me, maybe I'm missing something, but I'm getting consistent results in both FF and Chromium. I launch a browser, run JS code from revision#14, and get error message. Then I run code from revision#1 - it runs OK. Again I run 14's code - and no error message, it runs OK. So revision#14's code can not be run by itself?

@VadimR Thanks, fixed. That was a side-effect for testing it with a poluted environment. Needed to prefix the code with delete r; delete s; delete q; delete p; delete t; delete i; delete d; to ensure that it was not poluted.

q.trim()?q+'\n':'' could be q.trim()&&q+'\n', saving two. Also, i<p.length could just be p[i].

Ruby, 208 201 189
Very fun challenge!  Here's an alternative Ruby solution.
gets.size.times{|x|0.upto(h=$_[x].to_i-1){|d|r=$*[h-d]||=' '*~/$/
[x+d,x-d].map{|o|r[o]=r[o]>?!??v:o<x ??/:?\\if r[o]<?w}
d<1?r[x]=?^:r[x-d+1,w=2*d-1]=?w*w}}
puts$*.reverse.*($/).tr(?w,' ')

As a bonus, here's a Ruby implementation of Victor's very clever "cellular automaton" algorithm, at 162 characters:
s=gets
9.downto(1){|h|$0=(-1..s.size).map{|x|$_=$0[x,3]
s[x]=="#{h}"??^:~/  [\^\/]/??/:~/[\^\\]  /??\\:~/[\^\\] [\^\/]/??v:' '}*''
$*<<$0[1..-2]if$0=~/\S/}
puts$*

Example output:
....5.....6..6.....
          ^  ^
    ^    / \/ \
   / \  /      \
  /   \/        \
 /               \
/                 \

I think you may use $/ for newline.

C# - 588 characters - not as good as Ray's 321 though!
class P{static void Main(string[] a){char[,] w=new char[a[0].Length+1,10];int x=0;foreach(char c in a[0]){if(c!='.'){int h=int.Parse(c+"");if(w[x,h]=='\0')w[x,h]='^';int s=1;for(int l=h-1;l>0;l--){for(int m=x-s;m<=x+s;m++){if(w[m,l]!='\0'){if(w[m,l]=='^')w[m,l]='/';if(w[m,l]=='\\')w[m,l]='v';}else{if(m==x-s)w[m,l]='/';else if(m==x+s)w[m,l]='\\';else w[m,l]='\0';}bool t=false;for(int f=9;f>0;f--){if(t)w[m,f]='\0';if(w[m,f]!='\0')t=true;}}s++;}}x++;}for(int k=9;k>0;k--){string u="";for(int j=0;j<w.GetLength(0);j++){u+=w[j,k];}if(u.Replace("\0","")!="")System.Console.WriteLine(u);}}}

Example output:
F:\>mountains ".2..3..4..."
       ^
    ^ / \
 ^ / v   \
/ v       \

Or a longer more complex one...
F:\>mountains ".2..3..6.....5...3......1..3..4....2."
       ^
      / \    ^
     /   \  / \               ^
    /     \/   \ ^         ^ / \
 ^ /            v \       / v   \  ^
/ v                \    ^/       \/ \

Brilliant puzzle... not as easy as it seems... loved it!

"Complex one" is ill-formed, there's no peak for "3".

All the 3s are there. If you're talking about the first one, it's part of the slope.

APL, 65 bytes
⍉⌽↑⌽¨h↑¨'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a←11|⎕d⍳⍞]
⍞ this symbol returns raw (not evaluated) input as a character array.
Solving interactively, in an APL session:
      s←'...4...3...3..' ⍝ let's use s instead of ⍞
      ⎕d ⍝ the digits
0123456789
      ⎕d⍳s ⍝ the indices of s in ⎕d or 11-s if not found
11 11 11 5 11 11 11 4 11 11 11 4 11 11
      11|⎕d⍳s ⍝ modulo 11, so '.' is 0 instead of 11
0 0 0 5 0 0 0 4 0 0 0 4 0 0
      a←11|⎕d⍳s ⍝ remember it, we'll need it later
      ⍴a ⍝ length of a
14
      ⍳⍴a
1 2 3 4 5 6 7 8 9 10 11 12 13 14
      ⍝ ∘.-    subtraction table
      ⍝ ∘.-⍨A  same as: A ∘.- A
      ⍝ |      absolute value
      |∘.-⍨⍳⍴a
 0  1  2  3 4 5 6 7 8 9 10 11 12 13
 1  0  1  2 3 4 5 6 7 8  9 10 11 12
 2  1  0  1 2 3 4 5 6 7  8  9 10 11
 ...
13 12 11 10 9 8 7 6 5 4  3  2  1  0
      ⍝ ↓      split the above matrix into rows
      ⍝ a-     elements of "a" minus corresponding rows
      ⍝ ⊃⌈/    max them together
      ⊃⌈/a-↓|∘.-⍨⍳⍴a
2 3 4 5 4 3 3 4 3 2 3 4 3 2
      ⍝ This describes the desired landscape,
      ⍝ except that it's a little too high.
      ⍝ Add -1 to correct it:
      ¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a
1 2 3 4 3 2 2 3 2 1 2 3 2 1
      ⍝ Perfect!  Call it "h":
      h←¯1+⊃⌈/a-↓|∘.-⍨⍳⍴a
      0,⍨h ⍝ append a 0 (same as h,0)
1 2 3 4 3 2 2 3 2 1 2 3 2 1 0
      0,0,⍨h ⍝ also prepend a 0
0 1 2 3 4 3 2 2 3 2 1 2 3 2 1 0
      2-/0,0,⍨h ⍝ differences of pairs of consecutive elements
¯1 ¯1 ¯1 ¯1 1 1 0 ¯1 1 1 ¯1 ¯1 1 1 1
      ⍝ this gives us slopes between elements
      2+/2-/0,0,⍨h ⍝ sum pairs: left slope + right slope
¯2 ¯2 ¯2 0 2 1 ¯1 0 2 0 ¯2 0 2 2
      ×2+/2-/0,0,⍨h ⍝ signum of that
¯1 ¯1 ¯1 0 1 1 ¯1 0 1 0 ¯1 0 1 1
      2+×2+/2-/0,0,⍨h ⍝ add 2 to make them suitable for indexing
1 1 1 2 3 3 1 2 3 2 1 2 3 3
      ⍝ Almost ready.  If at this point we replace
      ⍝ 1:/ 2:v 3:\, only the peaks will require fixing.
      ~×a ⍝ not signum of a
1 1 1 0 1 1 1 0 1 1 1 0 1 1
      (~×a)×2+×2+/2-/0,0,⍨h ⍝ replace peaks with 0-s
1 1 1 0 3 3 1 0 3 2 1 0 3 3
      ⍝ Now replace 0:^ 1:/ 2:v 3:\
      ⍝ We can do this by indexing a string with the vector above
      ⍝ (and adding 1 because of stupid 1-based indexing)
      '^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h]
///^\\/^\v/^\\
      ⍝ Looks like our mountain, only needs to be raised according to h
      r←'^/v\'[1+(~×a)×2+×2+/2-/0,0,⍨h] ⍝ name it for convenience
      h¨↑r ⍝ extend r[i] with spaces to make it h[i] long
 /  /   /    ^     \    \   /   ^    \   v  /   ^    \   \
      ↑⌽¨h¨↑r ⍝ reverse each and mix into a single matrix
/
 /
  /
   ^
  \
 \
 /
  ^
 \
v
 /
  ^
 \
\
      ⍉⌽↑⌽¨h¨↑r ⍝ reverse and transpose to the correct orientation
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \

Ruby, 390 characters
Whew, this one was tricky.
I ended up having to append to a new string for each character, using a variable s that meant "skip next character" which was needed for processing ^ and \.
This output exactly the given sample output for all of the test cases.
m=[gets.chomp]
a=m[0].scan(/\d/).max.to_i
m[0].gsub!(/./){|n|n==?. ? ' ':a-n.to_i}
s=nil
until a==0
o=''
m[-1].chars{|c|o+=case c
when ?0;?^
when ' ';t=s;s=nil;t ? '':' '
when /\d/;(c.to_i-1).to_s
when ?^;s=1;o.slice! -1;"/ \\"
when ?/;t=s;s=nil;t ? "#{o.slice! -1;' '}":o.slice!(-1)=='\\' ? 'v ':"/ "
when ?\\;s=1;' \\'
when ?v;' '
end}
m.push o
a-=1
end
puts (m[1..-1]*"\n").gsub /\d/,' '

Chart of what the variables mean:
m | The mountain array.
a | The highest height of a mountain. Used for counting when to stop.
s | Whether or not to skip the next character. 1 for yes, nil for no.
o | Temp string that will be appended to mountain.
t | Temp variable to hold the old value of s.

I'm sure I could golf it down much more, but I have to go now. Shall be improved later!

I'm struggling with the input .2.2. and can't see why it doesn't work.

Java, 377 407
Edit: @Victor pointed out that this needed to be a complete program, so I added a few dozen characters to make it compilable and runnable. Just pass the "purchase order" as the first param when executing the program, like so: java M ..3.4..6..4.3..
I think this is similar in spirit to other answers, basically just traverses the "mountain order" repeatedly for every possible height, and builds the mountains from the tops down. That way I only have to deal with four conditions if not building a peak -- either an up slope '/', down slope '\, joint 'v', or empty ' '. I can discover that simple by looking at the three spaces centered "above" my current position in my top-down build.
Note that like other submissions, I treat anything other than a number as equivalent to '.' in the input, for brevity.
Golfed version:
class M{public static void main(String[]m){char[]n=m[0].toCharArray();int e=n.length,h=9,x=-1,p;char[][]o=new char[11][e];char l,r,u;boolean a,b,c;for(;h>=0;h--){for(p=0;p<e;p++){if(n[p]-49==h){o[h][p]=94;if(x==-1)x=h;}else{l=(p>0)?o[h+1][p-1]:0;r=(p<e-1)?o[h+1][p+1]:0;u=o[h+1][p];a=l>91&&l<99;b=r==94||r==47;c=u<33;o[h][p]=(char)((a&&b)?'v':(c&&b)?47:(c&&a)?92:32);}}if(x>=h)System.out.println(o[h]);}}}

Human readable form (and without some of the equivalent transmogrifications to achieve golf form):
class Magrathea2 {
    public static void main(String[] mountain) {
        String out = "";
        char[][] output = new char[11][mountain[0].length()];
        int height = 9; int maxheight = -1;
        int position = 0;
        char left,right,up;
        char[] mount = mountain[0].toCharArray();
        for (; height >= 0; height--) {
            for (position=0; position < mount.length; position++) {
                if (mount[position]-49 == height) {
                    output[height][position] = '^';
                    if (maxheight==-1) {
                        maxheight=height;
                    }
                } else { // deal with non-numbers as '.'
                    left=(position>0)?output[height+1][position-1]:0;
                    right=(position<mount.length-1)?output[height+1][position+1]:0;
                    up=output[height+1][position];
                    if ((left=='^'||left=='\\')&&(right=='^'||right=='/')) {
                        output[height][position]='v';
                    } else if ((up==' '||up==0)&&(right=='/'||right=='^')) {
                        output[height][position]='/';
                    } else if ((up==' '||up==0)&&(left=='\\'||left=='^')) {
                        output[height][position]='\\';
                    } else {
                        output[height][position]=' ';
                    }
                }
            }
            if (maxheight >= height) {
                out+=new String(output[height]);
                if (height > 0) {
                    out+="\n";
                }
            }
        }
        System.out.println(out);
    }
}

Enjoy.
Example output:
$ java M ..3..4...6...5....1
         ^
        / \  ^
     ^ /   \/ \
  ^ / v        \
 / v            \
/                \^

The question mentions Write a complete program, so please, add the missing class X{public static void main(String[]z){.

Right on. I got misdirected by the next section of that sentence -- "or as argument" and missed the complete program part. I'll update it shortly.

Perl 6, 264 224 216 206 200 194 124 bytes
$_=get;my$a=10;((s:g/$a/^/;s:g/\s\.\s/ v /;s:g'\.\s'/ ';s:g/\s\./ \\/;$!=say TR/.1..9/ /;tr'^\\/v' ')if .match(--$a)|$!)xx 9

Thanks to @JoKing for showing a s/// solution. This is golfed a bit further after fixing the tr/// bug in Perl 6.
My original solution with subst:
my$t=get;for 9...1 {if $t.match($_)|$! {$t=$t.subst($_,'^',:g).subst(' . ',' v ',:g).subst('. ','/ ',:g).subst(' .',' \\',:g);$!=say $t.subst(/<[\.\d]>/,' ',:g);$t.=subst(/<[^\\/v]>/,' ',:g)};}

Ungolfed:
my $t=slurp;
my $s;
for 9...1 {
    if $t.match($_)||$s {                    # match number or latched
        $t=$t.subst($_,'^',:g)               # peaks
        .subst(' . ',' v ',:g)               # troughs
        .subst('. ','/ ',:g)                 # up slope
        .subst(' .',' \\',:g);               # down slope
        $s=say $t.subst(/<[\.\d]>/,' ',:g);  # clean, display, latch
        $t=$t.subst(/<[^\\/v]>/,' ',:g)      # wipe for next line
    }
}

Output:
...4...3...33..4..4....2.3.22.33.5..22...333.222.3..
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^^   \     ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      ^^  /   \^^^/ \
/        v           \/               \/           \

I don't think Perl strictly needs a main function, the entry point can just be the first thing outside a function.

I used main for parameter handling. Now using stdin. Thanks.

A procedural solution. I'm sure someone can do better with regexes and hyperops.

131 bytes using s/// and tr///. I think that last one can use tr instead of s but I can't quite figure out to translate backslashes. Maybe the first one too

Nice work @JoKing – I got into a topic mess when I tried to use s/// and TR///. I see that avoiding blocks is the answer.

125 bytes with the tr/// bug fixed. Also spurious > removed from TR/.1..9//
$_=get;my$a=10;((s:g/$a/^/;s:g/\s\.\s/ v /;s:g'\.\s'/ ';s:g/\s\./ \\/;$!=say TR/.1..9/ /;tr'^\\/v' ')if .match(--$a)|$!)xx 9

Nice! If you've got a shorter code, you should update the answer with the new program.

C# - 321 319
using System.Linq;class P{static void Main(string[]p){int h=p[0].Max()-48,i=h,j,n=p[0].Length;char[]A=new char[n+2],B=A;for(;i-->0;){for(j=0;j++<n;){var r=(A[j+1]==47|A[j+1]==94);B[j]=(char)(p[0][j-1]==i+49?94:i+1<h?A[j]==0?(A[j-1]>90&A[j-1]<95)?r?118:92:r?47:0:0:0);}A=(char[])B.Clone();System.Console.WriteLine(B);}}}

Ungolfed and commented:
using System.Linq;

class P
{
    static void Main(string[] p)
    {
        int h = p[0].Max() - 48,    // Getting the height. Codes for 0 to 9 are 48 to 57, so subtract 48 and hope no one will input anything but dots and numbers.
            i = h,
            j,                      // Declaring some iterators here, saves a few chars in loops.
            n = p[0].Length;
        char[] A = new char[n+2],   // Creating an array of char with 2 extra members so as not to check for "index out of bounds" exceptions
               B = A;               // B is referencing the same array as A at this point. A is previous row, B is the next one.
        for (;i-->0;)               // Looping from top to the bottom of the mountain
        {
            for (j = 0; j++ < n;)   // Looping from left to right.
            {
                var r = (A[j + 1] == 47 | A[j + 1] == 94);  // This bool is used twice, so it saves a few characters to make it a variable

                // Here's the logic
                B[j] = (char)(p[0][j - 1] == i + 49 ? 94    // If at this position in the string we have a number, output "^"
                                           : i + 1 < h ?    // And if not, check if we're on the top of the mountain
                                             A[j] == 0 ?    // If we're not at the top, check if the symbol above is a space (0, actually)
                                            (A[j - 1] > 90 & A[j - 1] < 95) ?   // If there's nothing above, we check to see what's to the left ( ^ or \ )
                                             r ?            // And then what's to the right ( ^ or / )
                                             118            // If there are appropriate symbols in both locations, print "v"
                                           : 92             // If there's only a symbol to the left, print "\"
                                           : r              // Otherwise check if there's a symbol to the right, but not to the left
                                           ? 47             // And if there is, print "/"
                                           : 0 : 0 : 0);    // Print nothing if there aren't any symbols above, to the left and to the right,
                                                            // or there's a "^" right above, or we're at the top of the mountain
            }
            A=(char[])B.Clone();    // Clone arrays to iterate over the next line
            System.Console.WriteLine(B);
        }
    }
}

Example:
C:\>program .2..3..4...
        ^
     ^ / \
  ^ / v   \
 / v       \

I think it outputs an extra space before each line, though.

Perl, 254 218 212
$s=<>;sub f{9-$i-$_[0]?$":pop}for$i(0..8){$h=1;$_=$s;s!(\.*)(\d?)!$D=($w=length$1)+$h-($2||1);join'',(map{($x=$_-int$D/2)<0?f--$h,'\\':$x?f++$h,'/':$D%2?f--$h,v:f$h,'/'}0..$w-1),$2?f$h=$2,'^':''!ge;print if/\S/}

$s=<>;
sub f{9-$i-$_[0]?$":pop}
for$i(0..8){
    $h=1;
    $_=$s;
    s!(\.*)(\d?)!
        $D=($w=length$1)+$h-($2||1);
        join'',(map{
            ($x=$_-int$D/2)<0
                ?f--$h,'\\'
                :$x
                    ?f++$h,'/'
                    :$D%2
                        ?f--$h,v
                        :f$h,'/'
        }0..$w-1),$2
            ?f$h=$2,'^'
            :''
    !ge;
    print if/\S/
}

Edit: actually it's a bug-fix to work with ProgrammerDan's ..3..4...6...5....1 example, but, in the process, some bytes were off. And online test: https://ideone.com/P4XpMU

CJam, 128 117 112 106 104 bytes
CJam is a bit younger than this challenge so this answer does not compete. This was a very nice challenge though! From the little I know about J and APL, I think a submission in those would be impressively short.
WlW++"."Waer{_{~U(e>:U}%\W%}2*;W%]z{$W=}%_$W=S*\:L,2-,\f{\_)L=(~"^/ ^^/ \v ^ \\"S/2/@L>3<_$0=f-{=}/t}zN*

Here is a test case, which I think contains all possible possible combinations of slopes, peaks and troughs:
...4...3...33..4..4....2.3.22.33.5..22...333.222.3..

which yields
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^/   \     ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      \^  /   \^^^/ \
/        v           \/               \/           \

Test it here.
I'll add an explanation for the code later.

Python, 297 234 218
-63 bytes thanks to Jo King
-16 bytes with r=s.replace instead of lambda
s=input()
r=s.replace
q=0
j=''.join
for i in range(9):
 if`9-i`in s or q:q=s=r(`9-i`,'^');s=r(' . ',' v ');s=r('. ','/ ');s=r(' .',' \\');print j([x,' '][x in'0123456789.']for x in s);s=j([x,' '][x in'/\^v']for x in s)

Takes input from STDIN.
Ungolfed, simplified:
s=input() # Take input
r=lambda y,z: s.replace(y,z) # Function for quick s.replace(a, b)
j=lambda x: ''.join(x)
q=0 # Acts like boolean
for i in range(9): # Count to 9
 if `9-i`in s or q: # When digit has been found or found previously (no newlines at start)
  q=s=r(`9-i`,'^') # Digit to ^, set q to non-zero value for always executing from now on
  s=r(' . ',' v ') # ' . ' to ' v '
  s=r('. ','/ ') # '. ' to '/ '
  s=r(' .',' k') # ' .' to 'k'. K is a placeholder, since \\ takes two chars and `[...]`[2::5] fails
  print j([x,' '][x in'0123456789.']for x in s) # Print without '0123456789.'
  s=j([x,' '][x in'/\^v']for x in s) # Wipe (delete '/^\v`)

234 bytes

Yeah, I tried the s.replace method myself, but it doesn't work. You're just performing replacements on the original string since strings are immutable

Powershell, 148 145 bytes
It's a nice challenge!
param($s)9..1|?{($p+=$s-match$_)}|%{"$_,^; \. , v ;\. ,/ ; \., \;\^|\\|/|v, "-split';'|%{$x=$s-replace'\.|\d',' '
$s=$s-replace($_-split',')}
$x}

Less golfed test script:
$f = {

param($s)
9..1|?{($p+=$s-match$_)}|%{      # loop digits form 9 downto 1, execute to the end as soon as a suitable digit met
    $s=$s-replace$_,'^'          # replace current digit with '^'
    $s=$s-replace' \. ',' v '    # replace ' . '  with ' v '
    $s=$s-replace'\. ','/ '      # replace '. ' with '/ '
    $s=$s-replace' \.',' \'      # replace ' .' with ' \'
       $s-replace'\.|\d',' '     # replace all dots and digits with ' ' and push to output. Don't store this replacement
    $s=$s-replace'\^|\\|/|v',' ' # prepeare to the next step: replace ^ \ / and v to space
}

    # Example:
    #     $s="...4...3...3.."
    # 4 : $s="...^...3...3.." output: "   ^          "
    # 4 : $s="... ...3...3.."
    # 3 : $s="../ \..^...^.." output: "  / \  ^   ^  "
    # 3 : $s="..   .. ... .."
    # 2 : $s="./   \/ \./ \." output: " /   \/ \ / \ "
    # 2 : $s=".        .   ."
    # 1 : $s="/        v   \" output: "/        v   \"
    # 1 : $s="              "

}

@(
    ,("1",
      "^")

    ,("11",
      "^^")

    ,("1.2.",
    "  ^ ",
    "^/ \")

    ,(".2.3..",
      "   ^  ",
      " ^/ \ ",
      "/    \")

    ,(".2..3..",
      "    ^  ",
      " ^ / \ ",
      "/ v   \")

    ,("...4...3...3..",
      "   ^          ",
      "  / \  ^   ^  ",
      " /   \/ \ / \ ",
      "/        v   \")

    ,("...4...3...33..4..4....2.3.22.3..5...22...333.222.3..",
      "                                 ^                   ",
      "   ^           ^  ^             / \                  ",
      "  / \  ^   ^^ / \/ \     ^    ^/   \      ^^^     ^  ",
      " /   \/ \ /  v      \  ^/ \^^/      \^^  /   \^^^/ \ ",
      "/        v           \/                \/           \")

    ,(".2..3..6.....5...3......1..3..4....2.",
      "       ^                             ",
      "      / \    ^                       ",
      "     /   \  / \               ^      ",
      "    ^     \/   \ ^         ^ / \     ",
      " ^ /            v \       / v   \  ^ ",
      "/ v                \    ^/       \/ \")
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$result"-eq"$expected"
    $s
    $result
}

Output:
True
1
^
True
11
^^
True
1.2.
  ^
^/ \
True
.2.3..
   ^
 ^/ \
/    \
True
.2..3..
    ^
 ^ / \
/ v   \
True
...4...3...3..
   ^
  / \  ^   ^
 /   \/ \ / \
/        v   \
True
...4...3...33..4..4....2.3.22.3..5...22...333.222.3..
                                 ^
   ^           ^  ^             / \
  / \  ^   ^^ / \/ \     ^    ^/   \      ^^^     ^
 /   \/ \ /  v      \  ^/ \^^/      \^^  /   \^^^/ \
/        v           \/                \/           \
True
.2..3..6.....5...3......1..3..4....2.
       ^
      / \    ^
     /   \  / \               ^
    ^     \/   \ ^         ^ / \
 ^ /            v \       / v   \  ^
/ v                \    ^/       \/ \

Pip -l, 100 bytes
Y#aZGMXaFi,#aIh:+a@i{(yi--h):4j:0Wh-j&++(yi-++jh-j)(yi+jh-j):2}RV Z(J*y)R`.(?=.*[^0])`0R,6;^" /\v^^"

(The language is newer than the question, but probably isn't going to beat the APL submission anyway. Although I hope it will get much shorter.)
Takes input via command-line argument. Try it online!

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


text:
king + rook vs king
It's the ending of another well played chess game. You're the white player, and you still have a rook and your king. Your opponent only has his king left.
Since you're white, it's your turn. Create a program to play this chess match. Its output can be a sequence of moves, a gif animation, ASCII art or whatever you like.
It seems quite obvious, but I'll state it explicitly: you have to win the game (in a finite number of moves). It's always possible to win from this position. DO NOT LOSE THAT ROOK. DO NOT STALEMATE.
Your program may or may not accept a human input for the starting position and for each black move (you can safely assume this is a legal position, i.e. the kings are not touching each other).
If it doesn't, a random starting position and random movements for the black king will suffice.
Score
Your score will be length in byte of your code + bonus. Any language is allowed, lowest score wins.
Bonus
-50 if your program allows both a human defined starting position and a random one. Humans can enter it via stdin, file, GUI...
-100 if your program allows both a human and a random player to move the black king
+12345 if you rely on an external chess solver or a built-in chess library
Good luck!
Update!
Extra rule: The match must be played until checkmate. Black does not resign, doesn't jump outside the chessboard and doesn't get kidnapped by aliens.
Hint
You can probably get help from this question on chess.se.

Don't forget to run your challenges through the Sandbox to test their readiness before posting.

Oh.. thank you. It's indeed the first question I ask, didn't know about this. And of course the first exploit has been posted...

Does the 50 move draw rule apply?

@Comintern If you don't move your pieces randomly, this game shouldn't last that long. You have to play the standard chess rules, thus you have to apply it, but it shouldn't affect the outcome.

Possibly relevant: http://chess.stackexchange.com/questions/4886/how-do-you-checkmate-with-a-rook

The bounty is expiring, no one?

The program will output the (optimal) moves for white. Should we substitute it with random moves for black?

@JAnderton either randomly or user input, bonus points awarded if your program handles both.

@Victor I've had a couple of goes, but it hasn't worked out yet. Brute force is obviously too slow, alpha-beta too because the landscape of position ratings is quite flat; and tends to get stuck in a loop. Retrograde analysis would work but very slow up-front. My next attempt will use Bratko's algorithm for KRK, which I've avoided because it's a pile of special cases, not great for golf.

Bratko's algorithm here for those who want to have a go, foot of page 599 http://books.google.co.uk/books?id=-15su78YRj8C&pg=PA609&lpg=PA609&dq=minimax+rook&source=bl&ots=TA3-081sNS&sig=Ea5Xujm6etTkyQIXoiz9MFUtqQQ&hl=en&sa=X&ei=cl0SU43HLIyshQemwoHQCQ&ved=0CH4Q6AEwDDgU#v=snippet&q=%20an%20advice%20program&f=false and a slightly simpler variant that always wins in ~30 moves (not the optimal 16) is described in http://argo.matf.bg.ac.rs/publications/2013/2013-icga-krk-sat.pdf

@victor I'm looking at this too. This is interesting precisely because it simple to define and difficult to do. In turn the program will not be short, so the code-golf tag made it seem doubly hard. If my program works you'll see it soon.

@bazzargh I don't think that the algorithm must be optimal. If it manages to eventually check-mate the black king and never stalemates or loses the white rook, I think that it will be valid.

@steveverrill I would suggest you to forget the golf and just post something that works, or just do the most basic golfs (remove whitespaces, rename variables to 1 char and not much more).

@Victor the problem was not about trying to be optimal, any attempt to pick a 'best' move without considering game history led to loops. Need to test game terminates from every position. Bratko+variants arent optimal but provably terminate. Trying retrograde analysis just now (ie build endgame table), looks promising and actually is optimal, which is nice. Also turns out reasonably short.

If anyone needs inspiration (or is just curious), you can find a 1433 character complete chess engine at http://home.hccnet.nl/h.g.muller/umax1_6.c

You might eventually want to add an image as it makes the question much nicer, e.g. http://i.imgur.com/j8nLthL.png created with http://www.apronus.com/chess/wbeditor.php

@izabera, was there a problem with my answer? surprised to see the longer one marked as the winner. Not taking offence, just wondering if you'd found a bug.

@bazzargh oh sorry i must have misclicked, sorry

@bazzargh deserves it more than me. I did reduce my program down to shorter than his by eliminating some of the input checking and renaming variables, in particular eliminating the subscripts for the piece positions (for example r[0] and r[1] for the rook becomes two variables R and r.) However I then found a few bugs, and working on them made the program slightly longer again. Being accepted confused me, so I stopped and went out. I don't see much point in fixing it now, the best man won.

@steveverrill I actually voted your entry up, and wouldn't have been annoyed if you got the win. After so many false starts on my entry, I can appreciate just how hard it was to get any answer working, and how hard the bugs are to find-I'd have code that appeared to work, but would go into a loop on certain moves 10 moves in. Tough, tough puzzle.

@bazzargh I told myself not to waste time on this cos I knew it would be hard. But then the doctor signed me off with flu and that was it. A little at a time till I got to the point where I was like "I WILL MAKE THIS WORK!" by which time the flu was better. Also I was determined to write an algorithm to play the actual game, but as you say something always came up 10 moves down and the computer won't think on the fly. Some kind of analysis, or failing that, some randomness in picking the white move, is probably the way to go. Good job and +1 (I was too engrossed to upvote before.)

Would a program that randomly moves king and rook such that the rook cannot be captured and no illegal moves and stalemates happen be a valid answer to this question? It succeeds in finite, yet random time, after all.

@Wrzlprmft you should be able to prove it does

@izabera: That’s not the problem. It will of course lead to a draw, if black invokes the fifty-moves rule or threefold repetition.

Haskell 1463-100=1363
Just getting an answer in. This finds the solution the retrograde way, working back from checkmate to the position we're in. It differs from the description of retrograde analysis on chessprogramming - instead of starting with an initial set and expanding it with backwards moves until no squares moved to haven't been seen, it starts with all unused squares and reduces that set by trying forward moves. This is going to be less time-efficient than the traditional way, but the memory usage exploded for me when I tried it.
Compile with ghc -O2 for acceptable performance for the endgame table calculation; play is instant after the first move. Supply white king, rook, black king squares as arguments. For a move, it just wants a square, and will pick one for you if you press return. Example session:
$ time  printf "\n\n\n\n\n\n\n\n"|./rook8 e1 a1 e8
("e1","a7","e8")[d8]?
("d2","a7","d8")[c8]?
("d2","h7","c8")[b8]?
("c3","h7","b8")[a8]?
("b4","h7","a8")[b8]?
("c5","h7","b8")[a8]?
("b6","h7","a8")[b8]?
("b6","h8","b8") mate

real    0m8.885s
user    0m8.817s
sys 0m0.067s

Code:
import System.Environment
import qualified Data.Set as S
sp=S.partition
sf=S.fromList
fl=['a'..'h']
rk=[0..7]
lf=filter
m=map
ln=notElem
lh=head
pl=putStrLn
pa[a,b]=(lh[i|(i,x)<-zip[0..]fl,a==x],read[b]-1)
pr(r,c)=fl!!r:show(c+1)
t f(w,r,b)=(f w,f r,f b)
km(a,b)=[(c,d)|c<-[a-1..a+1],d<-[b-1..b+1],0<=c,c<=7,0<=d,d<=7]
vd (w,r,b)=b`ln`km w&&w/=r&&b/=w&&b/=r
vw p@(_,r,b)=vd p&&r`ln`km b&&(ck p||[]/=bm p)
vb p=vd p&&(not.ck)p
rm (w@(c,d),(j,k),b@(u,x))=[(w,(j,z),b)|z<-rk,z/=k,j/=c||(k<d&&z<d)||(d<k&&d<z),j/=u||(k<x&&z<x)||(x<k&&x<z)]
kw(w,r,b)=m(\q->(q,r,b))$km w
xb(w,r,_)b=(w,r,b)
wm p=lf(\q->q/=p&&vw q)$rm p++(m(t f)$rm$t f p)++kw p
bm p@(_,_,b)=lf(\q->q/=p&&vb q)$m(xb p)$km b
c1((c,d),(j,k),(u,x))=j==u&&(c/=j||(k<x&&d<k)||(k>x&&d>k))
ck p=c1 p||(c1$t f p)
mt p=ck p&&[]==bm p
h(x,y)=(7-x,y)
v=f.h.f
f(x,y)=(y,x)
n p@((c,d),_,_)|c>3=n$t h p|d>3=n$t v p|c>d=n$t f p|True=p
ap=[((c,d),(j,k),(u,x))|c<-[0..3],d<-[c..3],j<-rk,k<-rk,u<-rk,x<-rk]
fr s p=S.member(n p)s
eg p=ef(sp mt$sf$lf vw ap)(sf$lf vb ap)
ps w mv b0=sp(\r->any(fr b0)$mv r)w
ef(b0,b1)w=let(w1,w2)=ps w wm b0 in(w1,b0):(if S.null w2 then[]else ef(f$ps b1 bm w2)w2)
lu((w1,b0):xs)p=if fr w1 p then lh$lf(fr b0)$wm p else lu xs p
th(_,_,b)=b
cd tb q=do{let{p=lu tb q};putStr$show$t pr p;if mt p then do{pl" mate";return()}else do{let{b1=pr$th$lh$bm p};pl("["++b1++"]?");mv<-getLine;cd tb$xb p (pa$if""==mv then b1 else mv)}}
main=do{p1<-getArgs;let{p2=m pa p1;p=(p2!!0,p2!!1,p2!!2)};cd(eg p)p}

Edited: Fixed code to remember endgame table and use arguments, so much less painful to test repeatedly.

haskell code with side effects? how could you, heretic! :p

finally a serious one!

that puzzle was evil @izabera!

Nice! Much better than the attempt I was working on.  I was trying to just improve the El Ajedrecista enough to ensure 50 move mates, but as far as an algorithm goes it's really bad.

A lot of the sucky performance comes from me not memoizing the endgame table (y). This is really obvious in that the second move isn't fast when we've already considered the whole endgame. I am off to the pub this evening but if I get the chance tomorrow I'll make this less terrible.

C, Currently 2552 noncomment nonwhitespace characters
The count indicates to me that I could golf it down below 2552 total chars, but given there is already a smaller answer (which will be tough to beat) I will consider that carefully before bothering to do it. It's true there's about 200 chars for displaying the board and another 200 each for checking user input of both start position and move (which i need for testing, but could eliminate.)
No game tree here, just hardcoded algorithm, so it moves instantly.
Start positions are entered as row (1-8) column (1-8) numbered from top right and the program works on the same scheme. So if you turned your screen 90 degrees anticlockwise, it would follow the standard Correspondence Chess numeric square notation. Positions where the black king is already in check are rejected as illegal.
Black moves are entered as a number from 0 to 7, with 0 being a move to the north, 1 to the northeast and so on in a clockwise sense.
It doesn't follow the commonly known algorithm that exclusively uses the rook under the protection of the white king to restrict the black king. The rook only restricts the black king in a vertical sense (and will run away horizontally if chased.) The white king restricts the black king in horizontal movement. This means the two white pieces do not get in each others' way.
I seem to have ironed out most of the bugs and possible infinite loops, it's running pretty well now. I will play with it again tomorrow and see if there is anything else that needs fixing.
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"

int b[2], w[2], r[2], n[2],s,t,i,nomate;
int v[2][8] = { {-1,-1,0,1,1,1,0,-1}, {0,1,1,1,0,-1,-1,-1} };
int u[5] = { 0, 1, -1, 2, -2 };
char empty[82] = "        \n--------\n--------\n--------\n--------\n--------\n--------\n--------\n--------\n";
char board[82];

int distance(int p[2], int q[2]){
    return __max(abs(p[0]-q[0]),abs(p[1]-q[1]));
}

int sign(int n){
    return (n>0)-(0>n);
}

// from parameters p for white king and q for rook, determines if rook is/will be safe
int rsafe(int p[2],int q[2]){
    return  distance(p, q)<2 | distance(q,b)>1;
}

void umove(){
    t=0;
    while (t != 100){
        printf("Enter number 0 to 7 \n");
        scanf_s("%d", &t); t %= 8;
        n[0] = b[0] + v[0][t];
        n[1] = b[1] + v[1][t];
        if (distance(w, n) < 2 | (n[0] == r[0] & (n[1]-w[1])*(r[1]-w[1])>0)
            | ((n[1] == r[1]) & (n[0]-w[0])*(r[0]-w[0])>0) | n[0] % 9 == 0 | n[1] % 9 == 0)
            printf("illegal move");
        else{ b[0] = n[0]; b[1] = n[1]; t = 100; };
    }
}

void imove(){
    t=0;
    // mate if possible
    if (distance(b, w) == 2 & b[0] == w[0] & (b[1] == 1 | b[1] == 8) & r[0]!=w[0]){
        n[0] = r[0]; n[1] = b[1];
        if (rsafe(w, n)){
            r[1] = n[1];
            printf("R to %d %d mate!\n", r[0], r[1]);
            nomate=0;
            return;
        }
    }

    //avoid stalemate
    if ((b[0] == 1 | b[0] == 8) & (b[1] == 1 | b[1] == 8) & abs(b[0] - r[0]) < 2 & abs(b[0]-w[0])<2){
        r[0] = b[0]==1? 3:6;
        printf("R to %d %d \n", r[0], r[1]);
        return;
    }

    // dont let the rook be captured.
    if(!rsafe(w,r))
    {
        if (w[0] == r[0]) r[1] = w[1] + sign(r[1]-w[1]);
        else r[1] = r[1]>3? 2:7;
        printf("R to %d %d \n", r[0], r[1]);
        return;
    }

    // if there's a gap between the kings and the rook, move rook towards them. we only want to do this when kings on same side of rook, and not if the black king is already on last row.
    if (abs(w[0]-r[0])>1 & abs(b[0] - r[0]) > 1 & (b[0]-r[0])*(w[0]-r[0])>0 & b[0]!=1 & b[0]!=8){
        n[0] = r[0] + sign(b[0] - r[0]); n[1] = r[1];
        if (rsafe(w, n)) r[0] = n[0];
        else r[1] = r[1]>3? 2:7;
        printf("R to %d %d \n", r[0], r[1]);
        return;

    }
    // if kings are far apart, or if they not on the same row (except if b 1 row from r and w 2 rows from r), move king
    if ((w[0]-r[0])!=2*(b[0]-r[0]) | abs(b[0]-w[0])>1 | distance(w,b)>2){
        for (i = 0; i<8; i++) if (v[0][i] == sign(b[0] - w[0]) & v[1][i] == sign(b[1] - w[1])) t = i;
        s = 1 - 2 * (w[0]>3 ^ w[1] > 3);
        for (i = 0; i < 5; i++){
            n[0] = w[0] + v[0][(t + s*u[i] + 8) % 8];
            n[1] = w[1] + v[1][(t + s*u[i] + 8) % 8] *(1-2*(abs(w[0]-b[0])==2));
            if (distance (n,b)>1 & distance(n, r)>0 & rsafe(n,r) & n[0]%9!=0 & n[1]%9!=0
                & !(n[0]==r[0] & (w[0]-r[0])*(b[0]-r[0])>0)) i = 5;
        }
        if (i == 6) {
            w[0] = n[0]; w[1] = n[1]; printf("K to %d %d \n", w[0], w[1]); return;
        }
    }

    //if nothing else to do, perform a waiting move with the rook. Black is forced to move his king.
    t = r[1]>3? -1:1;
    for (i = 1; i < 5; i++){
        n[0] = r[0]; n[1] = r[1] + t*i;
        if (rsafe(w, n)){ r[1] = n[1]; i=5; }
    }
    printf("R to %d %d \n", r[0], r[1]);
}

int _tmain(){

    do{
        t=0;
        printf("enter the row and col of the black king ");
        scanf_s("%d%d", &b[0], &b[1]);
        printf("enter the row and col of the white king ");
        scanf_s("%d%d", &w[0], &w[1]);
        printf("enter the row and col of the rook");
        scanf_s("%d%d", &r[0], &r[1]);
        for (i = 0; i < 2; i++) if (b[i]<1 | b[i]>8 | w[i]<1 | w[i]>8 | w[i]<1 | w[i]>8)t=1;
        if (distance(b,w)<2)t+=2;
        if ((b[0] == r[0] & (b[1]-w[1])*(r[1]-w[1])>0) | ((b[1] == r[1]) & (b[0]-w[0])*(r[0]-w[0])>0)) t+=4;
        printf("error code (0 if OK) %d \n",t);
    } while(t);

    nomate=1;
    while (nomate){
        imove();
        strncpy_s(board, empty, 82);
        board[b[0] * 9 + b[1] - 1] = 'B'; board[w[0] * 9 + w[1] - 1] = 'W'; board[r[0] * 9 + r[1] - 1] = 'R'; printf("%s", board);
        if(nomate)umove();
    }
    getchar(); getchar();

}

Here's a typical finish (mate can sometimes occur anywhere on the right or left edge of the board.)


text:
Finding Local Extremes
Write a function or program that takes in a list and produces a list of the local extremes.
In a list [x_0, x_1, x_2...] a local extreme is an x_i such that x_(i-1) < x_i and x_(i+1) < x_i or x_(i-1) > x_i and x_(i+1) > x_i. Notice that the first and last elements of the list can never be local extremes.
So for some examples
local_extremes([1, 2, 1]) = [2]
local_extremes([0, 1, 0, 1, 0]) = [1, 0, 1]
local_extremems([]) = []

This is code golf so the shortest code wins!

To make sure I understand correctly: Numbers greater than the numbers on either side?

@undergroundmonorail Greater or less than. So it either has to be a local minimum, where it's neighbors are both greater, or a maximum where they're both smaller

Oh, I see. I misread it

and what about sequence 1 2 2 1 shouldn't those 2 be considered as extremes too? - I know, this would make the solution much more difficult...

Mathematica 66  58 51
Current Solution
Shortened thanks to a contribution by Calle.
Cases[Partition[#,3,1],{a_,b_,c_}/;(a-b) (b-c)<0⧴b]&

Partition[#,3,1] finds the triples.
(a-b) (b-c)<0 is true if and only if b is below a, c, or above a,c.
and looks at takes the signs of the differences. A local extreme will return either {-1,1} or {1,-1}.

Examples
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{1, 2, 1}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{0, 1, 0, 1, 0}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

{2}
  {1, 0, 1}
  {}
  {10, 6, 9, 0, 1}

Earlier Solution
This looks examples all triples (generated by Partition) and determines whether the middle element is less than both extremes or greater than the extremes.
Cases[Partition[#,3,1],{a_,b_,c_}/;(b<a∧b<c)∨(b>a∧b>c)⧴b]& ;

First Solution
This finds the triples, and looks at takes the signs of the differences. A local extreme will return either {-1,1} or {1,-1}.
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}⧴x[[2]]]&

Example
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}:>x[[2]]]&[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

{10, 6, 9, 0, 1}

Analysis:
Partition[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]

{{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3,
    3}, {3, 3, 1}, {3, 1, 10}}

% refers to the result from the respective preceding line.
Differences/@ %

{{1, -3}, {-3, -1}, {-1, 3}, {3, -9}, {-9, 3}, {3, 0}, {0, -2}, {-2, 9}}

Sort@Sign@Differences@x=={-1,1} identifies the triples from {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, 3}, {3, 3, 1}, {3, 1, 10}} such that the sign (-, 0, +) of the differences consists of a -1 and a 1.  In the present case those are:

{{9, 10, 7}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {3, 1, 10}}

For each of these cases, x,  x[[2]] refers to the second term. Those will be all of the local maxima and minima.

{10, 6, 9, 0, 1}

Your Mathematica style is much more concise than mine. When do we start calling it "Wolfram Language"?

I see this

Michael Stern, I suspect Wolfram Language will only become official at version 10, some form of which already available on Raspberry Pi.

BTW, someone inserted a line of code that converts the Math ML to graphics.  I'm not sure why.

I'm not sure why he did it. I can't see any differences in the "modified" code

@DavidCarraher Just a comment on my first comment: I'm not playing the purist game. I don't need your fullform in order to believe your code runs:)! I was just telling you that your code doesn't show as expected in all browsers!

You appear to have found the shortest way to go through each number, I was surprised it wasn't ReplaceList (3 characters longer). However you can replace the way you check if a number is a local extreme and do it like some other answer here: ReplaceList[#,{___,x_,y_,z_,___}/;(x-y)(z-y)>0:>y]& This will make it even shorter. +1

belisarius, No criticism was intended.  I know and agree with your views about purism on this site.  I merely though you wanted to have code available that you could easily copy and paste.

Calle, Why don't you submit the solution you suggested? After all, it differs from mine in both the first and second parts.

J - 19 char
Couldn't help it ;)
(}:#~0,0>2*/\2-/\])

Explanation follows:

2-/\] - Over each pair of elements in the argument (each 2-item long infix), take the difference.
2*/\ - Now over each pair of the new list, take the product.
0> - Test whether each result is less than 0. This only happens if the multiplicands had alternating signs, i.e. it doesn't happen if they had the same sign or either was zero.
0, - Declare that the first element isn't an extreme element.
}: - Cut off the last element, because that can't possibly be an extreme either.
#~ - Use the true values on the right side to pick items from the list on the left side.

Usage:
   (}:#~0,0>2*/\2-/\]) 1 2 1
2
   (}:#~0,0>2*/\2-/\]) 0 1 0 1 0
1 0 1
   (}:#~0,0>2*/\2-/\]) i.0   NB. i.0 is the empty list (empty result also)

   (}:#~0,0>2*/\2-/\]) 3 4 4 4 2 5
2

Umm, this may not work if the input is, say, 3, 4, 4, 4, 4, 5, i.e. you may get a zero in the "0=" step if 0 is added to 0.

Also, I do not know about this language, but, instead of taking the signum in the first step, you can leave the difference as it is. Then, in the second step, multiply the elements instead, and in the third you may check if the product is negative (this also avoids that 0 problem). Perhaps this may result in a shorter code.

Good catch, and yes, this saves two characters. Updating.

Javascript - 62 45 Characters
f=a=>a.filter((x,i)=>i&&i<a.length-1&&(a[i-1]-x)*(a[i+1]-x)>0)

Edit
f=a=>a.filter((x,i)=>(a[i-1]-x)*(a[i+1]-x)>0)

Ruby, 83 70 60 55 49 characters
f=->a{a.each_cons(3){|x,y,z|p y if(x-y)*(z-y)>0}}

Prints all local extremes to STDOUT.
Uses the <=> "spaceship" operator, which I really like. (It returns 1 if the first thing is greater than the second, -1 if it's less, and 0 if equal. Therefore, if they add to -2 or 2, that means the middle is an extreme.)
Not anymore, as @daniero pointed out that the "obvious" way is actually shorter!
Changed yet again! Now it uses the awesome algorithm found in MT0's answer (+1 to him!).
Also, I like each_cons which selects each n groups of consecutive elements in an array. And trailing if is interesting too.
Overall, I just like how elegant it looks.
Some sample runs:
irb(main):044:0> f[[1,2,1]]
2
=> nil
irb(main):045:0> f[[1,0,1,0,1]]
0
1
0
=> nil
irb(main):046:0> f[[]]
=> nil
irb(main):047:0> f[[1,2,3,4,5,4,3,2,1]]
5
=> nil
irb(main):048:0> f[[1,1,1,1,1]]
=> nil
irb(main):049:0> f[[10,0,999,-45,3,4]]
0
999
-45
=> nil

It's shorter to unpack x into 3 variables: f=->a{a.each_cons(3){|x,y,z|p y if((x<=>y)+(z<=>y)).abs==2}}

@daniero Thanks; I didn't even know you could do that! Edited

really? :D Btw, now that each term is 3 character shorter, it's overall cheaper to do x>y&&y<z||x<y&&y>z (even tho the spaceship operator is very pretty) ;)

also... !((x..z)===y) is even shorter though not as clever

@Charles That fails when x < z.

@daniero Hmm, that's right! Edited, thanks again. (And I do know Ruby, but I didn't know that form of each_cons :P) Oh, and btw thanks for helping me beat Mathematica :P

@Doorknob good catch

C++ - 208 chars
Longest solution again:
#include<iostream>
#include<deque>
using namespace std;
int main(){deque<int>v;int i;while(cin){cin>>i;v.push_back(i);}for(i=0;i<v.size()-2;)if(v[++i]>v[i-1]&v[i]>v[i+1]|v[i]<v[i-1]&v[i]<v[i+1])cout<<v[i]<<' ';}

To use, enter your integers, then any character that will crash the input stream - any non-number characters should work.
Input: 0 1 0 x
Output: 1

You can use a deque instead of a vector to gain 2 characters.

Also, instead of using i and j, you can declare int i; right after the collection and use in is the two loops instead of declaring two variables.

Finally, you can probably get get rid of the increment i++ in your for loop and begin your condition by if(v[++i]>[i-1]... in order to gain one character again.

Jelly, 8 bytes
IṠIỊ¬T‘ị

Try it online!
Explanation
IṠIỊ¬T‘ị
I          Differences between adjacent elements {of the input}
 Ṡ         Take the sign of each difference
  I        Differences between adjacent difference signs
   Ị       Mark the elements that are     in the range -1..1 inclusive
    ¬                                 not
     T     Take the indexes of the marked elements
      ‘      with an offset of 1
       ị   Index back into the original list

An element is only a local extreme if its difference with its left neighbour has an opposite sign to its difference with its right neighbour, i.e. the signs of the differences differ by 2 or -2. Jelly has a number of useful primitives for dealing with "find elements with certain properties" (in particular, we can find elements with certain properties in one list and use that to extract elements from a different list), meaning that we can translate back to the original list more or less directly (we just need to offset by 1 because the first and last elements of the original list got lost in the difference-taking).

Python 2.7 - 73 bytes
e=lambda l:[l[i]for i in range(1,len(l)-1)if(l[i]-l[i-1])*(l[i]-l[i+1])]

Not too impressive (Look at every element of the list except the first and last, see if it's larger or smaller than its neighbours). I'm mostly only posting it because not everyone knows you can do x<y>z and have it work. I think that's kind of neat.
Yes, x<y>z is a cool feature of python, but it's not actually optimal in this case. Thanks to V-X for the multiplication trick, that didn't occur to me at all. Wrzlprmft reminded me that declaring an anonymous function is less keystrokes than def x(y):.

if(l[i]-l[i-1])*(l[i]-l[i+1])>0 would reduce the code by 11 characters...

@wrz Ah, you're right. I was thrown off by the fact that def e(l):\n  is the same number of characters as e=lambda l:, but I forgot that you don't need to use the return keyword. Thanks!

@v-x Oh, I like that a lot. Thank you :) edit: Actually you can save more than that! Since (l[i]-l[i-1])*(l[i]-l[i+1]) is 1 if l[i] is a local extreme and 0 otherwise, I don't need to use >0. I can just let python interpret it as a bool. :)

@wrz I can't figure out how to edit a comment that's already been edited (the pencil icon seems to replace the edit button. is this by design?). I just wanted to add that, if I was smart, I'd have realized that my one-line function didn't need the \n  in the declaration at all! That would have saved two characters, but the inclusion of return still makes it not worth it.

Matlab - 45 bytes
x=input('');y=diff(x);x(find([0 y].*[y 0]<0))

Haskell 50
f a=[x|(p,x,n)<-zip3 a(tail a)(drop 2 a),x>p&&x>n]

this only check local maximum, for minumum need to add || x<min p n

x>p&&x>n has one less character than x>max p n :-)

space after , is not necessary either.

change x>p&&x>n to (x>p)==(x>n) for local minimums too, adds 4 more chars.

05AB1E, 11 10 bytes
¥.±¥Ä2Q0šÏ

Try it online or verify a few more test cases.
Explanation:
¥           # Get the forward differences (deltas) of the (implicit) input-list
            #  i.e. [9,10,7,6,9,0,3,3,1,10] → [1,-3,-1,3,-9,3,0,-2,9]
 .±         # Get the signum of each delta (-1 if neg.; 0 if 0; 1 if pos.)
            #  → [1,-1,-1,1,-1,1,0,-1,1]
   ¥        # Get the forward differences of that list again
            #  → [-2,0,2,-2,2,-1,-1,2]
    Ä       # Convert each integer to its absolute value
            #  → [2,0,2,2,2,1,1,2]
     2Q     # And now check which ones are equal to 2 (1 if truthy; 0 if falsey)
            #  → [1,0,1,1,1,0,0,1]
       0š   # Prepend a 0
            #  → [0,1,0,1,1,1,0,0,1]
         Ï  # And only leave the values in the (implicit) input-list at the truthy indices
            #  → [10,6,9,0,1]
            # (after which the result is output implicitly)

Python with Numpy – 81 74 67 bytes (61 54 without the import line)
import numpy
e=lambda a:a[1:-1][(a[2:]-a[1:-1])*(a[1:-1]-a[:-2])<0]

The input needs to be a Numpy array.

C, 83
x,y,z;main(){y=z=0;while(scanf("%d",&x)){(y-z)*(y-x)>0?printf("%d ",y):1;z=y,y=x;}}

awk - 32 chars
{c=b;b=a;a=$0;$0=b}(b-c)*(a-b)<0

No hope of beating a language like J or APL on brevity, but I thought I'd throw my hat into the ring anyway. Explanation:

At any given time, a, b, and c hold x_i, x_(i-1), and x_(i-2)
b-c and a-b approximate the derivative before and after x_(i-1)
If their product is negative, then one is negative and the other is positive, therfore x_(i-1) is a local extreme, so print

Brachylog, 17 bytes
s₃{b≠h.&k≠&{⌉|⌋}}

Try it online!
Takes input through the input variable and generates the output through the output variable.
s₃{             }    For a length-3 substring of the input:
  {b                 its last two elements
    ≠                are distinct,
     h               and the first of those elements is
      .              the output variable;
       &k            its first two elements
         ≠           are also distinct;
          &{⌉| }     either its largest element
          &{ |⌋}     or its smallest element
                }    is also the output variable.

If runs of values could be guaranteed to be absent, s₃{{⌉|⌋}.&bh} would save four bytes.

Perl 5 -p, 49 bytes
s/\d+ (?=(\d+) (\d+))/say$1if($1-$&)*($1-$2)>0/ge

Try it online!

Wolfram Language (Mathematica), 43 42 41 bytes
BlockMap[#2&@@#/.Median@#->Set@$&,#,3,1]&

Try it online!
BlockMap[                       &,#,3,1]&   (* for every consecutive triple of elements *)
         #2&@@#                             (* take the second (middle) element, *)
               /.Median@#->Set@$            (* discarding it if it is not a local extreme *)

Javascript: 102 characters
function h(a){for(u=i=[];++i<a.length-1;)if(x=a[i-1],y=a[i],z=a[i+1],(x-y)*(y-z)<0)u.push(y);return u}

PHP, 116 114 113
function _($a){for(;$a[++$i+1];)if(($b=$a[$i])<($c=$a[$i-1])&$b<($d=$a[$i+1])or$b>$c&$b>$d)$r[]=$a[$i];return$r;}

Example usage:
print_r(_(array(2, 1, 2, 3, 4, 3, 2, 3, 4)));

Array
(
    [0] => 1
    [1] => 4
    [2] => 2
)

APL, 19 bytes
{⍵/⍨0,⍨0,0>2×/2-/⍵}

I converted the 20 char J version to APL. But I add a zero to the beginning and the end instead of removing the first and last digit. Otherwise it works just like the J version.
⍵ - formal parameter omega. This is the input to the function.

While we're at it, I have a K version, too, in 22 characters: {x@1+&0>2_*':-':0 0,x}. 6 of these characters (2_ and 0 0,) are spent protecting against a length error if the argument is shorter than two items, so if not for that problem it would be 16... The action is also a little different--we have to turn the boolean list into a list of indices with 1+& and use that to index x again--but it's shorter and also a very K-ish thing to do.

Your K version would beat my APL version then. My code needs at least two numbers.

Haskell, 70C
Golfed version
e(a:b:c:r)
 |a<b&&b>c||a>b&&b<c=b:s
 |True=s
 where s=e(b:c:r)
e _=[]

Ungolfed version
-- if it's possible to get three elements from the list, take this one
extrema (a:b:c:rest)
    | a<b && b>c = b:rec
    | a>b && b<c = b:rec
    | otherwise = rec
    where rec = extrema (b:c:rest)
-- if there are fewer than three elements in the list, there are no extrema
extrema _ = []

Python 2, 59 bytes
f=lambda l=0,c=0,*r:r and(c,)*(l<c>r[0]or l>c<r[0])+f(c,*r)

Try it online!
This function mostly avoids the costly business of indexing, by taking the elements of the list as arguments, instead of the list itself. While there is more than one element left in the list, we recursively build up the list, checking for a maximum at each step.


text:
Convert calendar dates to week dates and vice versa
Your mission is to write a program that accepts a date in the formats 2014-02-27 (calendar date) and 2014-W09-4 (week date) from standard input and outputs the date in the format it wasn't entered in (to standard output with a trailing newline). The dates must conform to the standard ISO 8601, i.e. with weeks that starts on Mondays and where the first week in a (week) year is the one that contains the first Thursday in the calendar year. You are not allowed to use any libraries, built-in functions or operators that relates to the handling of dates and time.
For example:
>./aprogramnamethatmostprobablyrelatestobutterfliesandbiscuits
2014-02-27
2014-W09-4
>./aprogramnamethatmostprobablyrelatestobutterfliesandbiscuits
2014-W09-4
2014-02-27
>./aprogramnamethatmostprobablyrelatestobutterfliesandbiscuits
2008-12-30
2009-W01-2
>./aprogramnamethatmostprobablyrelatestobutterfliesandbiscuits
2009-W53-7
2010-01-03
>

Years prior to 1583 and after 9999 need not yield the correct answer.
The shortest answer (in characters, not bytes) will be declared the winner and therefore accepted in 19½ days.
A nice resource: ISO week date

Prior to 1582 or prior to 1583?

What about operators? MySQL has the interval <x> <unit> (eg: 2008-12-30 + interval 53 weeks).

I do indeed mean 1583, sorry for my immensely confused range of years. I will immediately correct it.
Date and time related operators gives an immense advantage to a language, so they are henceforth disallowed.

See http://en.wikipedia.org/wiki/Zeller%27s_congruence for the answer.  I implemented this as a statement function in Fortran IV about 45 years ago but have lost the punch cards containing it.

Can we get some external informations, like which day of the week the years starts and how many days the month have? They aren't directly manipulation the data, but gathering precious information.

@IsmaelMiguel I think that this is part of the challenge, you would need to figure out the weekday of january first and decide how much days there are in each month (special attention to February).

1583 was the year of adoption of the Gregorian calendar in many countries. Some adopted it later (for political / religious reasons) but I assume we can ignore those countries. It would be worth spelling out that years that divide by 100 but not by 400 (such as 1800, 1900, 2100, 2200) are not leap years. This is to avoid a slow creep of the seasons and was the reason that Pope Gregory chose to change the calender.

@steveverrill The Gregorian calendar was adopted by the Catholic Church in september of 1582. So, 1583 was the first full year with the new calendar. Some countries, specially non-catholic, adopted it later (the last one was Greece in 1923).

Javascript: 422 characters
Originally this had 825 characters, and was still a bit comprehensible and legible, beside the fact of being golfed. I was sure that it could be reduced in something between 10% to 20%. This answer passed by tons of edits from me and got suggestions from @Ismael Miguel and specially from @DocMax resulting in an extremely-golf-crushed source down to 422 characters, with the side-effect of making it heavily obfuscated, a reduction of almost 49%. Really thanks for both, I wish that you two could get a badge for this. I did not thought that it could be reduced by so much.
Here is the code, 422 characters:
x=prompt(E=eval);W=x[f=5]=='W';A=x.match(/\d+/g);y=+A[a=0];for(t="'012011223445569'[z]-30+30*z";q=a%4<1&(a%100>0|a%400<1),a++<y;f=(f+1+q)%7)v=f;z=w=+A[1]-W;r=+A[2];if(W){w+=f>3;h=7*w+r-f;for(z=1;h-q*(z>2)>=E(t);++z);w=1+(10+z--)%12;d=h-q*(z<3)-E(t);y+=z?z>12:-1}else{g=r+E(t)-(w>1&&!q+w-2?2-q:2);d=(f+g)%7;w=0|g/7+(f<4);w=w>11&r-d>26?(++y,1):w<1?(--y,53^v>3):w}alert(y+(W?'-':'-W')+(w>9?'':0)+w+'-'+(!W|++d>9?'':0)+d+'\n')

Pretty complex. Here a (somewhat long) partially-ungolfed (but still badly obfuscated) and commented version:
x = prompt(E = eval); // Receives input, but has a side-effect of having a strange message in the prompt box.

// Year 0 of the Gregorian calendar (if such thing existed) would start on a 5=Friday. (0=Monday, 6=Sunday)
W = x[f = 5] == 'W'; // Checks if there is a W in the sixth char.
A = x.match(/\d+/g); // Divide the input in 3 numbers.

y = +A[a = 0]; // Parse the year.

// The t variable is used to create a table with cumulative months length starting from December of the previous year, this table is acessed by using the eval() function.
// Calculate the weekday of 01/01 of the year in the f variable. Do that by counting Gregorian calendar years from 0 until now.
// Count 2 weekdays for leap years and 1 for non-leap years.
// The variable q defines if the year is a leap year.
// The v variable stores the weekday of 01/01 of the prevoius year.
// The % 7 ensures that the weekday are kept in the interval 0-6, where 0 is Monday and 6 is Sunday.
for (t = "'012011223445569'[z] - 30 + 30 * z"; q = a % 4 < 1 & (a % 100 > 0 | a % 400 < 1), a++ < y; f = (f + 1 + q) % 7)
  v = f;

z = w = +A[1] - W; // Parse the second number, might be the week number or the month, accordingly to the W.
r = +A[2]; // Parse the third number, might be the week day or the day in the month, accordingly to the W.

// Converts week date to calendar date.
if (W) {

  // The expression "7 * (f > 3) - f" maps the offset between the calendar date and the week date in the following manner:
  // {0Mon:1, 1Tue:0, 2Wed:-1, 3Thu:-2, 4Fri:4, 5Sat:3, 6Sun:2}
  // Obtain the day within the year and store it in h.
  w += f > 3;
  h = 7 * w + r - f;

  // Finds the day offset in the table to the corresponding month.
  for (z = 1; h - q * (z > 2) >= E(t); ++z);

  // This calculates the day in the month and the month.
  w = 1 + (10 + z--) % 12;
  d = h - q * (z < 3) - E(t);

  // Fix-up the year, if needed.
  y += z ? z > 12 : -1

// Converts calendar date to week date.
} else {

  // Calculate how many days passed since 01/01
  g = r + E(t) - (w > 1 && !q + w - 2 ? 2 - q : 2);

  // Knowing the week day in which the year started and how many days passed since 01/01, calculate the week day of the given date.
  d = (f + g) % 7;

  // Calculates how many weeks passed since 01/01 and add one week if the year started on Monday, Tuesday, Wednesday or Thursday.
  w = 0 | g / 7 + (f < 4);

  // If we are in the last 3 days of the year, and 01/01 will fall on Monday, Tuesday, Wednesday or Thursday,
  // then we advance to the first week of the next year.
  // Do this by checking r + 3 - (d - 2) > 31, where:
  //   r is the date;
  //   (d - 2) is the weekday (d=1 for monday, 7 for sunday);
  //   (3 - (d - 2)) is the number of days until the week's Thursday and;
  //   > 31 means January of the next year.
  // r + 3 - (d - 2) > 31 is simplified to r - d > 26.
  w = w > 11 & r - d > 26 ? (++y, 1)

  // If we are at the 0th week of the year, go back to the last week of the previous year.
  // If the last year started on Friday, Saturday or Sunday this would be the 52nd week. It is the 53rd otherwise.
    : w < 1 ? (--y, 53 ^ v > 3)

  // Neither of the previous two cases.
    : w
}

// Output it.
alert(y + (W ? '-' : '-W') + (w > 9 ? '' : 0) + w + '-' + (!W | ++d > 9 ? '' : 0) + d + '\n')

The prompt box comes with the message with the serialization of the eval function. Ignore this message, it is just a side-effect of golfing some chars.
It passes for all provided test cases. If given invalid input, the behaviour is undefined.
Here are the test cases, had some bugs in previous versions (specially with the last two lines):
2014-02-27  <-->  2014-W09-4
2008-12-30  <-->  2009-W01-2
2010-01-03  <-->  2009-W53-7
2011-04-23  <-->  2011-W16-6
2012-01-01  <-->  2011-W52-7

In case you are curious, here it is the original, 825 characters code:
p=parseInt;x=prompt();y=p(x.substr(0,4));f=6;j="a%4<1&(a%100>0|a%400<1)";for(a=1583;a<y;a++)f+=eval(j)?2:1;f%=7;q=eval(j);if(x.contains('W')){w=p(x.substr(6,2))-1;r=p(x.substr(9))-1;u=f<1?3:f<5?1-f:f-4;h=w*7+r+u+1;e=q?1:0;d=h<1?(m=12,y--,h+31):h<32?(m=1,h):h<60+e?(m=2,h-31):h<91+e?(m=3,h-59-e):h<121+e?(m=4,h-90-e):h<152+e?(m=5,h-120-e):h<182+e?(m=6,h-151-e):h<213+e?(m=7,h-181-e):h<244+e?(m=8,h-212-e):h<274+e?(m=9,h-243-e):h<305+e?(m=10,h-273-e):h<335+e?(m=11,h-304-e):h<366+e?(m=12,h-334-e):(m=1,y++,h-365-e);alert(y+'-'+(m<10?'0':'')+m+'-'+(d<10?'0':'')+d+'\n')}else{m=p(x.substr(5,2));d=p(x.substr(8));g=d-1;for(b=1;b<m;b++)g+=[31,q?29:28,31,30,31,30,31,31,30,31,30,31][b-1];v=(f+g)%7;w=~~(g/7)+(f>0&f<5?1:0);if(v<1)w--,v=7;if(m>11&d>28&32-d+f>3)w=1,y++;if(w<1)w=53,y--;alert(y+'-W'+(w<10?'0':'')+w+'-'+(v<1?7:v)+'\n')}

You can reduce your code a few bytes by creating u='substr' and instead of using x.substr(), you can use x[u](). And instead of x.contains('W'), try /w/i.test(x). And that  w = ~~(g / 7) + (f > 0 & f < 5 ? 1 : 0) can be replaced with w=~~(g/7)+!!f&5. Just for the performance sake, try replacing all i++ with ++i (i is just an example var).

@IsmaelMiguel Thanks. I did all your changes except the !!f&5. I used the longer ~~(f>0&f<5) instead. The reason is that !!f&5 gave me 1 for 5 and 6, meaning that it would mess-up years starting on Fridays or Saturdays.

Then instead of !!f&5 you still can do (f>0&f<5) (without the ?1:0), which has the same effect

@IsmaelMiguel Thanks, reduced further 2 chars.

Sorry bothering you again, but you can change this f += eval(j) ? 2 : 1; for f += 2-!eval(j); or f += 1+!eval(j);. And where you have s = q ? h - 1 : h; you can replace by s = h-!!q;, reducing more 3 chars. And where you have ([dm] < 10 ? '0' : ''), you can replace with ([dm]>9?'':0) saving more 2 chars for each substitution. On your array, replace q ? 29 : 28 with 29-!q. I believe that there are other tiny details, but I think you can cut down almost 12 chars with these tips.

To go even further, you can create a var r=alert and a var e=eval. This will save around 3 bytes.

@IsmaelMiguel Thanks for bothering me again. I did what you suggested in your first comment after my previous one (and could save 3 more chars). About your last comment, doing that would increase one char instead, so I didn't.

You can save 25 chars by replacing [31,29-!q,31,30,31,30,31,31,30,31,30,31][b-1] with b-2?30+b%2^b>7:29-!q, calculating the days of the month instead of looking it up.

@Docmax Thank you. Done :). I guess that the same should be possible with the long ternary expression about the d, but I am busy with other things now, so will look for this later.

@Victor, You can move the u='substr' to the line below, replacing it with y = p(x[u='substr'](0, 4)), reducing another char. And about the output where you have (w > 9 ? '' : '0'), using (w > 9 ? '' : 0) is supposed to produce the same output with less 2 chars.

@IsmaelMiguel Thank you, reduced more 7 chars.

Because parseInt('1234-') returns 1234, there is no need for the first substr call. That, combined with moving the assignment to u into the prompt call to save a semicolon will save 9 more chars. Net result: replace p=parseInt;x=prompt();y=p(x[u='substr'](0,4)) with p=parseInt;y=p(x=prompt(u='substr')).

@Docmax thank you. Done. After that, i could reduce more 4 characters too.

Where you have u = f < 1 ? 1 : f < 5 ? 1 - f : 8 - f; you can reduce to u = f < 1 ? 1 : (7 * ! f < 5 ) - f;. And where you have 1+!!eval, you can reduce to 2-!eval. And where you have s = h - !!q; you can reduce to s = h + !q;

6 more bytes in two changes: replace u=f<1?1:f<5?1-f:8-f;h=w*7+r+u+1 with h=w*7+r+(f<1?2:f<5?2-f:9-f) (it looks like u isn't used after this) and ~~(g/7) with 0|g/7.

I saw Ismael Miguel's comment on u after I posted mine. Combining the two, you get h=w*7+r+f<1?1:(7*!f<5)-f+1. Also, since the code presumes properly formatted input, save another 3 replacing /w/i.test(x) with x[5]=='W'.

@IsmaelMiguel Thanks one more time. The u optimization looks like that it fails with Fridays and Saturdays, so I used DocMax idea instead. Your other 2 ideas were implemented.

@DocMax, I am just testing for the h=w*7+r+f<1?1:(7*!f<5)-f+1. If it works, I will place it. This is somewhat hard to test as it works differently for different years.

My h=... incorporates IsmaelMiguel's piece, so if that does not work, my "new" h won't either.

The first two statements inside the if and else are the same differing in the starting index and subtracting one. If you replace if(x[5]=='W'){w=p(x[u](6))-1;r=p(x[u](9))-1; with W=x[5]=='W';w=p(x[u](5+W))-W;r=p(x[u](8+W))-W;if(W){ and else{m=p(x[u](5));d=p(x[u](8)) with else{ (which requires replacing m with w and d with r in the else clause), it shaves off another 18.

@DocMax Looks like that the code is currently broken for 2011. Inputting 2011-04-23 outputs 2011-W16-6 correctly, but going the another way gives 2011-04-24. Using h=w*7+r+f<1?1:(7*!f<5)-f+1 makes it worse (it goes to 2010). Lets debug this thing...

It's the h-!!q to h+!q conversion. For 2011-W16-06, h=113 and q=0 giving 113 vs. 114 for the expression.

let us continue this discussion in chat

One more: you can shave another character from the (w>1&&!q+w-2?!q:1) by using the boolean bitwise rule, to make (w>1&!q+w-2?!q:1).

@WallyWest No, it is necessary to be && instead of & there. That was on purpose. If I use & it would bug the case 2008-12-30 --> 2009-W01-2 which would incorrectly produce 2009-W01-1 instead.

Reduced further from 451 to 446 by changing the base year from 1582 to 0 and taking some golfing opportunities from this.

C: 286 characters
In a quite unorthodox fashion I will give an entry to my own challenge (but I will not accept this answer even if it is the shortest when the time comes), just to show another (much less elegant than the JS-solution) way to attack the problem.
I[9],C[9],W[9],Y,M=5,D,y,w,d;main(){for(gets(I);sprintf(C,"%d-%02d-%02d",Y,M,D),sprintf(W,"%d-W%02d-%d",y,w,d),(strcmp(I,C)||puts(W)<0)&&(strcmp(I,W)||puts(C)<0);++D>28+(M^2?M+(M>7)&1^2:!(Y&3)&&(Y%25||!(Y&15)))&&(D=1,M=M%12+1)<2&&Y++,(d=d%7+1)<2&&(M>11&&D>28||M<2&&D<5?(w=1,y++):w++));}

I simply simulate the calendars day by day, increasing the month, week, year and week-year as needed. When either the week date or calendar date is equal to what was inputted I output the date in the format it wasn't inputted in (so if the input is invalid it will simply loop forever).
In a slightly more readable form:
I[9],C[9],W[9],Y,M=5,D,y,w,d;
main(){
        for(
                gets(I);

                sprintf(C,"%d-%02d-%02d",Y,M,D),
                sprintf(W,"%d-W%02d-%d",y,w,d),

                (strcmp(I,C)||puts(W)<0)&&
                (strcmp(I,W)||puts(C)<0);

                ++D>28+(M^2?M+(M>7)&1^2:!(Y&3)&&(Y%25||!(Y&15)))&&
                (D=1,M=M%12+1)<2&&Y++,

                (d=d%7+1)<2&&
                (M>11&&D>28||M<2&&D<5?(w=1,y++):w++)
        );
}