text:
Cross-matching regular expressions
Your task here is to write two regular expressions, each of which matches the other one but does not match itself.
Both regular expressions should have this form:
/pattern/optional-flags

This is also the form in which they should be matched.
The shortest solution wins. The solution length is counted as the sum of characters in both regular expressions including slashes and flags.
Use a regex syntax standard of your choice, or specify a programming language, when it makes a difference.
Have fun!

Does the regex also have to match the slashes and flags of the other regex?

@ProgramFOX yes, I added a line to make it clear.

Can you define match? i.e. does the regex /a/ match abc?

@TheGuywithTheHat well, I think so, unless you choose a language that imposes certain restrictions, like the need to match the whole string. Does this address your concern?

To be clear: I assume that the use of different delimiters (as permitted by e.g. PHP PCRE) is not permitted? (I.e. no submitting /^%/ and %^/%)

@PeterTaylor you're right. There are ways to create a regular expression that don't even need you to use a delimiter. The syntax requirements are there to keep the rules simple and clear. They're not just arbitrary limitations.

This is very quine-like, should it be tagged quine?

@Cruncher, the only output produced is a couple of Booleans. It doesn't fit the current definition of the [tag:quine] tag, and that definition fits pretty well with what I understand to be the standard meaning of the term.

@PeterTaylor That's generally why we call them variants. If I had a program that returned true when the input was its own source, and false otherwise, that would be very quine-like without ever fitting the output requirements of a true quine. In fact the question exists http://codegolf.stackexchange.com/questions/11370/write-the-shortest-self-identifying-program-a-quine-variant and is tagged quine.

PRCE with the A modifier: 9 chars
/A$/
/.A/A

Although this is a variant on Doorknob's /modifier$/ answer, I think this innovation qualifies it as a separate answer rather than a comment on his: the modifier does double-duty. Rather than being there solely for the other regex to match, it anchors.
The first regex matches any string ending in a literal A. The second regex matches any string whose second character is a literal A, using an anchor-to-start flag.
Online demo

To beat this requires only four non-delimiter chars, and since // matches anything that means that each of the regexes can have at most three non-delimiter chars. Using PHP PCRE there are 73339 non-self-matching regexes within that constraint, and exhaustive checking of the pairs whose length is less than 10 (on the order of 32Mpairs rather than 5.7Gpairs because most of them are 5 chars including delimiters) turns up this solution and no others. I therefore claim that it is optimal for that particular regex engine.

4+6=score of 10
First regex:
/i$/

Second regex:
/^.i/i

Hooray for flag abuse! :-P
The first one matches anything that ends with i (therefore, any regex with the i flag).
The second one matches anything with a second character of i.
Alternative version: /i$/g and /g$/i.

Another variation would be /x.$/ and /^.x/ for a bunch of x

Or /i$/ and /\/$/i

Or /i$/ and /i\$/i

JavaScript regexes, score: 18
First regex:
/^[^a]+$/

Second regex:
/^[^b]+$/

JavaScript test:
var regex1 = "/^[^a]+$/";
var regex2 = "/^[^b]+$/";
alert(/^[^a]+$/.test(regex2)); // true: regex1 matches regex2
alert(/^[^b]+$/.test(regex1)); // true: regex2 matches regex1
alert(/^[^a]+$/.test(regex1)); // false: regex1 doesn't match regex1
alert(/^[^b]+$/.test(regex2)); // false: regex2 doesn't match regex2

Test online: http://jsfiddle.net/99Sx6/

Ruby regex, 15
Regular expressions:
/.{9}/
/^.{06}$/

Just counting characters...
Online version
r1 = '/.{9}/'
r2 = '/^.{06}$/'

p r1 =~ /^.{06}$/ #0:   r2 matches r1
p r2 =~ /.{9}/    #0:   r1 matches r2
p r1 =~ /.{9}/    #nil: r1 doesn't match r1
p r2 =~ /^.{06}$/ #nil: r2 doesn't match r2

4 + 6 = 10
First regex:
/i$/

Second regex:
/\/$/i

i$ matches something that ends with i, the second one. /$ matches something that ends with /, the first one.

Dupe of a comment I posted to Doorknob's answer.

@PeterTaylor Didn't notice the comments until now. These were independent discoveries.

Yeah, I independently discovered shiona's version too.

5 + 5 = 10
Regex #1:
/0.$/

Regex #2:
/^.0/

The 0s in both regexes can be replaced with any non-metacharacter and the regex still works.
0.$ matches anything whose second last character is 0, and ^.0 matches anything whose second character is 0.

The first pair aren't valid regexes: you need to escape the /es. The alternative is a dupe of a comment on Doorknob's answer.

Score: 5 + 5 = 10
Took me half-an-hour to figure out but I am really happy that I did :)
1st is: /j.$/
2nd is: /^.j/
The 1st matched a j occurring in the second position starting from the right. The 2nd matches a j occurring at the second-position starting from left.
I haven't tested but I think that these RegExs are really versatile as the j can be replaced with any \w character (or more?) and still should work fine.
P.S. This should (hopefully) work in any language. Though, if it does not work in any, please inform in the comments below :)
Test

And I figure out now that @Quiccunx has already posted the same version as mine. I am really sorry Quiccunx and if it shall please any, I shall delete my answer.

JavaScript regexes, score: 13
First regex:
/\d/

Second regex:
/^[^0]+$/

Explanation: the first regex matches everything that contains a digit, and the second regex matches everything that doesn't contain a 0.
JavaScript test:
var regex1 = "/\d/";
var regex2 = "/^[^0]+$/";
alert(/\d/.test(regex2)); // true: regex1 matches regex2
alert(/^[^0]+$/.test(regex1)); // true: regex2 matches regex1
alert(/\d/.test(regex1)); // false: regex1 doesn't match regex1
alert(/^[^0]+$/.test(regex2)); // false: regex2 doesn't math regex2

Test online: http://jsfiddle.net/5VYjC/1/

12 chars ;) JS regex
/\d/
/0?\/$/g

PCRE using modifier x: 11 chars
/\s/
/ s.$/x

The first matches any string with a whitespace character, but doesn't contain whitespace. The second contains whitespace, but it's ignored because of the x modifier; it matches any string whose penultimate character is s.
PCRE and other engines using character classes: 11 chars
/\w+w/
/\Ww/

The first matches any string with a "word" character (letter, digit, underscore) followed by a literal w; the second matches any string with a non-word character followed by a literal w.
PCRE and other engines using character classes and word boundary anchor: 11 chars
/\w\w/
/\bw/

The first matches any string with two consecutive "word" characters; the second any string with a non-word character or start of string followed by a literal w.

ECMAScript (11 bytes):
/^\1?d/
/\d/

Other REGEXP Engines (14 bytes):
/^\\\\1?d/
/\d/

The 1st matches \d[..] or \1d[..].
The second matches any string with a number.
EDIT:
Originally, this answer was posted as being compatible with all engines, but it was proven to be wrong.
There was a problem with references to the capturing groups (for example, in php).

Many regex engines take the regex without surrounding slashes, but the question is quite clear in requiring them to be counted.

I am not counting it as an answer. Let me add the note for that.

@PeterTaylor I added the note. The Apache version is there just because.

Hang on: in what engines does the first one parse with \1 not interpreted as a back-reference?

Depending on the way you use it. In php, for example, if you put inside "/^\1?d/" you will have trouble, but if you do '/^\1?d/', then it's fine. The quotes make a huge difference when the code is interpreted.

No: in PHP if you do '/^\1?d/' you get preg_match(): Compilation failed: reference to non-existent subpattern at offset 5.

I have edited the answer and added a new solution for PHP.

Doesn't seem to work in ECMAScript either: http://fiddle.jshell.net/e9tWs/

The example code doesn't load on chrome and opera 12-16 on windows xp.


text:
DVORAK Keyboard layout
Here's an interesting challenge...
I want you to golf code that when executed will allow your input to be converted to mimic output as though you were typing on a DVORAK keyboard layout.
The aim is to mimic the US Simplified Dvorak Keyboard (US:SDK)

In comparison, here is the standard US QWERTY layout:

The keyboard emulation must work for both uppercase and lower case letters as well as shifted keys, for example, if I tapped the q (unshifted) key on my keyboard, the Dvorak code should pop out a ' character on the screen. If I were to tap the c (unshifted) button I should get a j (also unshifted) in response, C (shifted) would get J (shifted) and so on...
I am only concentrating of course on the white keys in the diagram above. Tabs, Caps and the other grey keys should work as per normal...
Any questions? Not for now? Good...
I will not allow external resources that already have the layout encoded already, I will not have any files brought in that can encode the layout. The code MUST be QWERTY INPUT -> (DVORAK RE-CODING) -> DVORAK OUTPUT in nature. No silly Esolangs that are theoretical or just say something like "This program will take QWERTY input and recode it in DVORAK. This is the program." or crap like that... Take this challenge seriously... So Brainfuck coders, I welcome you.
Please note, this is NOT a string conversion program. For every QWERTY key you press, the corresponding DVORAK character must be outputted...
Shortest code wins...

I think you need to specify a standard QWERTY layout if you want this to be a fair challenge. I suggest using this one.

Point taken, implemented...

Is it really necessary to pop a DVORAK character when I type a QWERTY character, or is it also OK to accept a QWERTY string as input and convert it to a DVORAK string?

@JanDvorak We are waiting for your solution ;)

It is ESSENTIAL that the respective key on the QWERTY keyboard generates the respective DVORAK response... This is NOT string manipulation... This is Key-for-Key conversion.

I don't fully understand. If string manipulation is prohibited, does it mean that stdin is out of the question? So I have to implement some low-level keyboard IO that reads keypresses? This also disqualifies brainfuck, which only reads strings from the stdin. What about stdout, can I send strings to the stdout or do I need to code a keyboard driver of sorts which simulates pressing a different key?

@fejesjoco are you referring to the last sentence? I read that as "STDIN must be read from and STDOUT written to without buffering"

You can read a string from stdin and write it to stdout with buffering. You can do the same unbuffered, with characters (getchar/putchar in C), or do both for different directions. But it's essentially the same thing, it won't yield very different programs. So I don't understand why this distinction is necessary. Reading key events (where you get a scancode, not a character) is something else, which would fit the question, but it's too lowlevel, and changing key events is essentially device driver stuff...

Should backspace delete a character from stdout? I think that would be the only sensible way to interpret the "this is not string manipulation" bit.

As an aside, your questions seem to always generate a large discussion in the comment thread. Maybe it is a sign you should be using the sandbox more?

@TimSeguine Quite possibly, but all I was expecting was code that took STDIN and produced the DVORAK equivalent to STDOUT... Sighs
At least Jan Dvorak has read that perfectly...

Shell: Unix tr(1), 94
tr \''"+-/:-[]_b-{}' "-_}w[vzSsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+"

This command takes QWERTY on stdin and outputs DVORAK on stdout.

Darn, you beat me to it!

@TheDoctor I just happened on this question early enough ☻ took me a while (about 20 minutes?) to optimise e.g. the ranges, though.

C - 144 characters
main(c){putch((c=getch())>33?c:"_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/\\
=^{`axje.uidchtnmbrl'poygk,qf?|+~"[c-34]);main(0);}

Nice solution ;-)

C#, 360 characters
Probably not the shortest, but it does exactly what you ask:
using System;class A{static void Main(){string[] q={"-=qwertyuiop[]sdfghjkl;'zxcvbnm,./","_+QWERTYUIOP{}SDFGHJKL:\"ZXCVBNM<>?","[]',.pyfgcrl/=oeuidhtns-;qjkxbmwvz","{}\"<>PYFGCRL?+OEUIDHTNS_:QJKXBMWVZ"};while(true){var c=Console.ReadKey(true);var a=c.KeyChar;int i,w=c.Modifiers==ConsoleModifiers.Shift?1:0;Console.Write((i=q[w].IndexOf(a))>-1?q[w+2][i]:a);}}}

If you press a key on your QWERTY keyboard, then the correct DVORAK character appears in the console.

AutoHotKey, 200 bytes
-::[
=::]
q::'
w::,
e::.
r::p
t::y
y::f
u::g
i::c
o::r
p::l
[::/
]::=
s::o
d::e
f::u
g::i
h::d
j::h
k::t
l::n
`;::s
'::-
z::`;
x::q
c::j
v::k
b::x
n::b
,::w
.::v
/::z

There should be an answer in AHK for this question but not. So just post one.

Shouldn't there be a "return"?

@MilkyWay90 OP didn't ask for halting. And this program will continue run until you manually exit it by clicking tray menu. So, no "return" involved.

Oh okay thank you for the explanation.

R, 157 bytes
Simple translate script.
chartr('\'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:"zZxXcCvVbBnN,<.>/?=_+-','-\'",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[',scan(,''))

Try it online!

Python, 181 bytes
print(input().translate(str.maketrans("'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:\"zZxXcCvVbBnN,<.>/?=_+-","-'\",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[")))

This code takes QWERTY on stdin and outputs DVORAK on stdout.
It does this by creating a translation table from qwerty to dvorak then translates stdin with input() using that translation table
A cleaner representation
print(
    input().translate(
        str.maketrans(
            "'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:\"zZxXcCvVbBnN,<.>/?=_+-",
            "-'\",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[",
        )
    )
)

Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Extract name of website from an absolute URL
You will take input such as
http://examples.example.co.nz/abcdefg
and return the name of the website, in which this example would be example.
To be more specific, I am looking for the Second Level Domain, which immediately precedes the TLD (Top Level Domain), but the Third Level Domain if the website is a Country Code Second-Level Domain.
Shortest bytes wins (competition ends March the 5th)!

Wouldn't it be examples.example.com?

@Strigoides Let me make it more specific

What would the expected result be for http://foo.bar.co.nz?

@Strigoides Uh... bar, I guess..?

Edited to make it more clear what you are looking for. Still, the end result of this approach to getting the site name is going to be pretty poor in many cases. Del.icio.us, Blo.gs, Instagr.am. Even stats.stackexchange.com, in which the third-level domain is the most significant identifier, but even then it is not the title of the site, which is Cross Validated.

In your example, the SLD is co.

@PeterTaylor Jonathan edited that in, I wasn't the one who confused you.  I've edited it now so it's more specific.

Aha. The question could still use improvement: firstly to define an authoritative source on which SLDs are ccSLDs, and secondly to define behaviour when the input isn't in that exact format (e.g. may we assume that the URL is always http? May we assume that it's an absolute URL? May we assume that the domain is never a TLD? May we assume that it never includes a username, password, or port number component?

@PeterTaylor ^That's exactly the exact... yes, okay, adding to answer

I've reviewed this question 4 times! enough closing and reopening!

I don't think the edits address any of my five requests for clarification.

Sounds like this could have used some time in the Sandbox... where we could have buried it with the proper rites.

Ruby, 15 characters
Assuming input is stored in variable s.
s.split(?.)[-2]

GolfScript, 7
Exact translation.
"."/-2=

Ruby with edge cases, 28
Such as http://example.com/foo.bar
s.split(?/)[2].split(?.)[-2]

GolfScript with edge cases, 13
"/"/2="."/-2=

This doesn't work for the case I asked about (a url containing a ccSLD). Not sure how you're supposed to distinguish between, say foo.co.nz (foo) and subdomain.co.com (co) though. The question seems a little underspecified.

I'm not even gonna try. Golfscript and co just ruin all the fun

@TheDoc That's no reason to downvote. Should I downvote all Java answers just because I don't like that language? You're still free to answer in whatever language you want; there's nothing stopping you.

@Doorknob But it means that me and my python will never win

@TheDoc That's pretty bad sportsmanship, downvoting all answers that beat yours. There's notHing stopping you from answering in Python.

@TheDoc Please do not vote on the language used in a post...

@Doorknob Unless the post is full of foul language. ;-)

@Doorknob - well, you downvoted me for disallowing Golfscript

@TheDoc Yes, I downvote posts that have arbitrary and unnecessary restrictions. There is absolutely no reason to disallow a language.

@TheDoctor You know, me and my C++, Java, and Python 3 have never one either.

@TheDoctor I've never won with my knowledge of GolfScript, CJam, and Pyth. (Not that I know much Pyth)

JavaScript, 27 bytes
Assuming a is the variable and c is a 1 or 0,
i=a.split('.')[i.length-c];

would work.  c is set to 3 if the domain is a ccsld and set to 2 if the domain isn't a ccsld.  c can also be edited to a larger number if the page has dots in it.

Uhhh, x==false?y:z is the exact same as x?z:y.

Ummm, I'm not sure what you're saying...

...when did I say that? Read my comments carefully...

@Doorknob Oh, yes... :)

What about i[i.length-ccsld-2]?

You could combine all three lines into i=a.split(".")[i.length-c];

C, 120
char s[999],*p,*q,*r;main(){gets(s);for(q=p=strstr(s,"//")+2,*strstr(p,"/")=0;*p;p++)if(*p=='.')*p=0,r=q,q=p+1;puts(r);}

Python - 30
Python's not too good for these things.
a.split("/")[2].split(".")[-2]

Doesn't work for TLDs with more than one ..

This doesn't work with the listed example - returns 'co' instead of 'example'.

@user17752 Ah - I guess it only works for general TLDs with one .. Since there can be an arbitrary number of .s in a URL, how can this work? Especially with the new custom TLDs?

The 2 "solutions' above fail, what if the website has the URL www.some1.name.ext/whatever.this/www/?
The solution in JavaScript is:
var arr = myurl.split('/');
var domain = arr[2];
var arr2 = domain.split('.');
var name = arr2[arr2.length-2];

or
name = myurl.split('/')[2].split('.')[myurl.split('/')[2].split('.').length-2];

Please golf your code and state the length (remove redundant space, use one-letter variable names...).

Python2 172, Python3 156
This one is long, but i think it fullfills all the requeriments of the question.
s = "http://examples.example.co.nz/abcdefg"

#BEGIN_CODE
import re,urllib2
l=re.findall("..",urllib2.urlopen("http://goo.gl/molpki").read())
m=re.search(r"(?:\w+\.)*(\w+)\.(\w+)\.(\w+)",s)
g=m.groups()
r=g[0]if g[2]in l else g[1]
#END_CODE

print(r)

l contains a list of all country codes from wikipedia
m contains the last third, second and first level domains, dropping all the others
r contains the result
All could go in a line, but since ; is the same as \n i leave it like this.
EDIT:
Tested with www.some1.name.ext/whatever.this/www/? and returns name so i guess it works.
Python 3 version
import re,requests as u
g=re.search(r"(?:\w+\.)*(\w+)"+"\.(\w+)"*2,s).groups()
r=g[0]if g[2]in re.findall("..",u.get("http://goo.gl/molpki").text) else g[1]

Same as above, r contains result.

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

authors: Αλέξανδρος Ζεγγ


text:
The Tic-tac-toe Games
Create a deterministic program to play nd tic-tac-toe with the other contestants.
Your program should work when n (width) and d (dimension number) are in these ranges:
n∈[3,∞)∩ℕ  ie a natural number greater than 2
d∈[2,∞)∩ℕ  ie a natural number greater than 1

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.
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, ....
Should this be the first move, the input will a number followed by 1 blank line.
For consistency, the input will always end with a newline. Sample Input (\n is newline):
10,10\n0,0,0,0,0,0,0,0,0,0;0,2,3,4,5,6,7,8,9,0;0,1,2,3,4,5,6,7,8,9\n

For first move:
10,10\n\n

where \n is the newline character.
Output:
Output the move you wish to make in the same format as the input (a comma-separated list). An invalid move (ie one that has already been taken) will result in a loss for the game.
Note: You can use a random number generator, as long as you seed it with a value such that each run would be identical given the same conditions. In other words, the program must be deterministic.
Note: only valid moves are allowed.
Winning Games (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>

Simulation and Winning Conditions:

State in your answer if it is ready for grading. That is, clearly indicate whether or not your answer is done.
If your answer is marked as done, it will not be graded until at least 24 hours after the last edit to the code.
Programs must work offline. If a program is found to be cheating, it will automatically receive a score of -1, and will not be scored further. (How would anyone end up with their programs cheating?)
If your program produces invalid output, it is immediately counted as a loss for the game
If you program fails to produce output after 1 minute it is immediately counted as a loss for the game.  If necessary, optimize for speed. I don't want to have to wait an hour to test a program off of another.
Each program will be run against the other programs twice for each n in the range [3,6] and each d in the range [2,5], once as X and once as O. This is one round.
For each game a program wins, it gets +3 to its score. If the program tied (1 win and 1 loss in a single round or ties for both games), then it gets +1. If the program lost, then it gets +0 (ie no change).
The program with the highest score wins. Should there be a tie, then the program with the least number of lost games (out of the tied contestants) wins.

Note: Depending on the number of answers, I may need help running the tests.
Good luck! And may the simulations run ever in your favor!

Win-checker challenge. <---- This challenge is to create programs to check if a certain game is won. It is very related to this challenge.

The [tag:self-contained] tag which you just invented doesn't add anything to the tag classification. I think you should remove it.

@Howard Okay. I noticed that a lot of questions had that restriction, so I thought a tag would be appropriate.

A strange game. The only winning move is not to play.

is (w,x,y,z) a valid output format?

@ali0sha Please output with the given format; this is to give a master program ability to check the answers.

So just to be sure you want the input appended with another move? Or just the numbers without brackets? You've specified the input well but for output you just have 'output the move you wish to make'

@ali0sha Sorry, I meant comma-separated like the input. Assuming you have some iterable, you could just do ','.join(list) (this only works if each element in the list is a string.)

Observation: The search space may be reduced by a factor of (2^d)*d!, which is the number of ways the dimensions can be mirrored and/or transposed.

Python 3
import random as rand
import re

def generateMoves(width, dim):
    l = [0] * dim
    while existsNotX(l, width - 1):
        yield l[:]
        for i in range(dim):
            if l[i] < width - 1:
                l[i] += 1
                break
            else:
                l[i] = 0
    yield l

def existsNotX(l, x):
    for i in l:
        if i != x:
            return True
    return False

input_s = input()
dims, moves = None, None
#this is to allow input as a single paste, instead of ENTER inputting.
try:
    dims, moves = input_s.splitlines()
except ValueError:
    dims = input_s
    moves = input()

rand.seed(moves + dims)

dims = eval(dims) #change into tuple

moves = moves.split(';')
if len(moves[0]):
    moves = [eval(m) for m in moves] #change into tuples

output =[x for x in generateMoves(dims[0], dims[1]) if x not in moves]
print(re.sub('[^\\d,]', '', str(output[rand.randint(0, len(output))])))

This is simply a random ai. It randomly selects a move out of the moves that are still available.

Python 2.7
This is a work-in-progress submission which I'm providing to give a skeleton/inspiration to other answerers. It works by listing every possible winning line, then applying some heuristic to score that line according to how valuable it is. Currently, the heuristic is blank (super-secret workings).
I have also added win and clash error handling.
Notes on the problem
How many winning lines are there? Consider the 1-dimensional case; there are 2 vertices, 1 edge, and 1 line. In 2 dimensions, we have 4 vertices joined by 2 lines, and 4 edges joined by 2*n lines. In 3 dimensions, we have 8 vertices joined by 4 lines, 12 edges joined by 6*n lines, and 6 faces joined by 3*n^2 lines.
In general, let us call a vertex a 0-facet, an edge a 1-facet, etc. Then let N(i) denote the number of i-facets, d the number of dimensions, and n the side length. Then the number of winning lines is 0.5*sum(N(i)*n^i,i=0..d-1).
Per wikipedia, N(i)=2^(d-i)*d!/(i!*(n-1)!), so the final formula is:
sum(2^(d-i-1) n^i  d! / (i! * (n-i)!),i=0..d-1)
which wolfram|alpha doesn't like very much. This gets very large pretty quickly, so I don't expect my program to have manageable runtime for d>8.
Some results (sorry about the formatting:
d\n 0   1    2      3      4       5        6        7         8         9
0   1   1    1      1      1       1        1        1         1         1
1   2   4    6      8      10      12       14       16        18        20
2   4   11   26     47     74      107      146      191       242       299
3   8   40   120    272    520     888      1400     2080      2952      4040
4   16  117  492    1437   3372    6837     12492    21117     33612     50997
5   32  364  2016   7448   21280   51012    107744   206896    368928    620060
6   64  1093 8128   37969  131776  372709   908608   1979713   3951424   7352101
7   128 3280 32640  192032 807040  2687088  7548800  18640960  41611392  85656080
8   256 9834 130809 966714 4907769 19200234 62070009 173533434 432891129 985263594

I/O
At the moment, the input needs to be input as: tictactoe.py <ret> n,d <ret> move;move <ret> - note the multiple lines and no final ;.
The output looks like (x_1,x_2,x_3...), for instance:
tictactoe.py <ret> 6,5 <ret> <ret> => 0, 0, 0, 0, 0
tictactoe.py <ret> 6,5 <ret> 0,0,0,0,0;0,0,0,0,5 <ret> => 0, 0, 0, 5, 0
# Notes on terminology:
#
# - A hypercube is the region [0,n]^d
# - An i-facet is an i-dimensional facet of a hypercube,
#   which is to say, a 0-facet is a vertex, a 1-facet an
#   edge, a 2-facet a face, and so on.
# - Any tuple {0,n}^i is a vertex of an i-hypercube
#   which is why I've used vertex to describe such
#   tuples
# - A winning line is a set of n coordinates which joins
#   two opposite i-facets
# - i-facets are opposite if they differ in every co-
#   ordinate which defines them
#
# Test Data:
#

import numpy
import itertools

def removeDuplicates(seq):
    noDupes = []
    [noDupes.append(i) for i in seq if not noDupes.count(i)]
    return noDupes

def listPairedVertices (i,n):
    """
    listPairedVertices returns a list L of elements of {0,n}^i which has the
    property that for every l in L, there does not exist l' such that
    l+l' = {n}^i.
    """

    vertices = numpy.array([[b*(n-1)  for b in a] for a in [
        list(map(int,list(numpy.binary_repr(x,i)))) for x in range(2**i)
    ]])
    result = []
    while len(vertices)>1:
        for j in range(len(vertices)):
            if numpy.all(vertices[j] + vertices[0] == [n-1]*i):
                result.append(vertices[0])
                vertices=numpy.delete(vertices,[0,j],axis=0)
                break
    return result

def listSequences (d,l):
    """
    listSequences returns the subset of {0,1}^d having precisely n 1s.
    """
    return numpy.array([
        r for r in itertools.product([0,1],repeat=d) if sum(r)==l
    ])

def listPaddedConstants (s,n):
    """
    listPaddedConstants takes a sequence in {0,1}^d and returns a number in
    {0..n}^sum(s) padded by s
    """
    result = numpy.zeros([n**sum(s),len(s)],dtype=numpy.int)
    for i,x in enumerate([list(z) for z in
        itertools.product(range(n),repeat=sum(s))]):
        for j in range(len(s)):
            if s[j]: result[i][j] = x.pop()
    return result

def listWinningVectorsForDimension(d,i,n):
    """
    List the winning lines joining opposite i-facets of the hypercube.

    An i-facet is defined by taking a vertex v and a sequence s, then forming
    a co-ordinate C by padding v with zeroes in the positions indicated by s.
    If we consider s = s_0.e_0 + s_1+e_1... where the e_j are the canonical
    basis for R^d, then the formula of the i-facet is
        C+x_0.s_0.e_0+x_1.s_1.e_1...
    for all vectors x = (x_0,x_1...) in R^n

    We know that winning lines only start at integral positions, and that the
    value of a will only be needed when s_j is nonempty, so the start point S
    of a winning line is in fact determined by:
     + vertex v in {0,n}^(d-i), padded by s
     + a in R^i, padded by the complement of s, s'

    Having performed the following operations, the co-ordinates of the winning
    lines are abs(S-k*s') for k in [0..n-1]
    """
    vertices = listPairedVertices(d-i,n)
    sequences = listSequences(d,i)
    result = []
    for s in sequences:
        for v in vertices:
            C = [0]*d
            j = 0
            for index in range(d):
                if s[index]: C[index] = 0
                else:
                    C[index] = v[j]
                    j+=1
            result += [
                [numpy.absolute(S-k*(numpy.absolute(s-1))) for k in range(n)]
                    for S in [C+a for a in listPaddedConstants(s,n)]
            ]
    return result

def AllWinningLines (d,n):
    """
    has the structure [[x_1,x_2,x_3],[y_1,y_2,y_3]] where each l_k is a
    length-d co-ordinate
    """
    result = []
    for i in range(d):
        result += listWinningVectorsForDimension(d,i,n)
    return result

def movesAlreadyMade ():
    """
    Returns a list of co-ordinates of moves already made read from STDIN
    """
    parameters = raw_input()
    moves = raw_input()
    parameters = list(map(int,parameters.split(',')))
    moves = [map(int,a.split(',')) for a in moves.split(';')] \
        if moves != '' else []
    return {'n':parameters[0], 'd':parameters[1], 'moves':moves}

def scoreLine (moves, line, scores, n):
    """
    Gives each line a score based on whatever logic I choose
    """
    myMoves          = moves[0::2]
    theirMoves       = moves[1::2]
    if len(moves)%2: myMoves, theirMoves = theirMoves, myMoves

    lineHasMyMove    = 0
    lineHasTheirMove = 0
    score            = 0

    for coord in line:
        if coord.tolist() in myMoves:
            lineHasMyMove += 1
            if coord.tolist() in theirMoves: raise Exception('Move clash')
        elif coord.tolist() in theirMoves: lineHasTheirMove += 1

    if lineHasMyMove == len(line):
        raise Exception('I have won')
    elif lineHasTheirMove == len(line):
        raise Exception('They have won')
    elif lineHasMyMove and lineHasTheirMove:
        pass
    elif lineHasTheirMove == len(line)-1:
        score = n**lineHasTheirMove
    else:
        score = n**lineHasMyMove

    for coord in line:
        if coord.tolist() not in moves:
            scores[tuple(coord)]+=score

def main():
    """
    Throw it all together
    """
    data      = movesAlreadyMade()
    dimension = data['d']
    length    = data['n']
    lines     = AllWinningLines(dimension, length)
    scores    = numpy.zeros([length]*dimension, dtype=numpy.int)

    try: [scoreLine(data['moves'], line, scores, length) for line in lines]
    except Exception as E:
            print 'ERROR: ' + E.args[0]
            return
    print ','.join(map(
        str,numpy.unravel_index(numpy.argmax(scores),scores.shape)
        ))

if __name__ == "__main__": main()

Edit: for I/O, added logic. I believe this is now ready to mark
Note that this comment was initially a placeholder which I deleted and undeleted.

Python 2
import re
import itertools

input_s = raw_input()
dims, moves = None, None
#this is to allow input as a single paste, instead of ENTER inputting.
try:
    dims, moves = input_s.splitlines()
except ValueError:
    dims = input_s
    moves = raw_input()

dims = eval(dims) #change into tuple

moves = moves.split(';')
if len(moves[0]):
    moves = [eval(m) for m in moves] #change into tuples

allSpaces = [x for x in itertools.product(range(dims[0]), repeat=dims[1])]
move = None
for space in allSpaces:
    if space not in moves:
        move = space
        break
print(re.sub('[^\\d,]', '', str(move)))

Most of the code is exactly the same as Quincunx's random AI. Instead of randomly selecting a move, it picks the first available move lexicographically (i.e. (0,0,...0), then (0,0,...1), then (0,0,...2), etc.).
This is a pretty rubbish strategy, but it almost always beats playing at random.