text:
Given a table of wins, losses and draws, output the result of each match in a sports tournament
This question is inspired by ongoing tournament of "the hooligan's game played by gentlemen", the Rugby World Cup, which has just completed the pool stage. There are 20 teams in the tournament, and they are divided into 4 pools of 5 teams each. During the pool stage each team plays against all the other teams in their pool (a total of 10 matches per pool), and the top 2 teams of each pool progress to the knockout stage.
At the end of the pool stage there is a table for each pool showing the number of wins, losses and draws for each team. The challenge for this question is to write a program that inputs the count of wins, losses and draws for each team in a pool, and from that information outputs the individual results of each of the 10 matches (who won, lost or drew against who) if possible or outputs an error message if not.
For example, here is the table for Pool D of this year's tournament:
            Win    Loss    Draw
Canada        0       4       0
France        3       1       0
Ireland       4       0       0
Italy         2       2       0
Romania       1       3       0

From this information, we can deduce that Ireland won against Canada, France, Italy and Romania, because they won all their games. France must have won against Canada, Italy and Romania but lost to Ireland, because they only lost one and it must have been to the undefeated Ireland. We have just worked out that Italy lost to Ireland and France, so they must have won against Canada and Romania. Canada lost all their games, and so Romania's win must have been against Canada.
         Canada  France Ireland   Italy Romania
Canada        -       L       L       L       L
France        W       -       L       W       W
Ireland       W       W       -       W       W
Italy         W       L       L       -       W
Romania       W       L       L       L       -

Here's a more complicated (fictional) example:
            Win    Loss    Draw
Canada        3       1       0
France        1       2       1
Ireland       0       3       1
Italy         0       2       2
Romania       4       0       0

In this case, we can deduce that Romania won against Canada, France, Italy and Ireland, because they won all their games. Canada must have won against Ireland, Italy and France but lost to Romania. We have just worked out that Italy lost to Romania and Canada, so they must have drawn against France and Ireland. That means Ireland drew with Italy and lost to everyone else, and therefore France must have beaten Ireland, drawn with Italy and lost to Canada and Romania.
         Canada  France Ireland   Italy Romania
Canada        -       W       W       W       L
France        L       -       W       D       L
Ireland       L       L       -       D       L
Italy         L       D       D       -       L
Romania       W       W       W       W       -

Some tables are unsolvable, for example this year's Pool B, in which 3 teams got the same W/L/D totals:
            Win    Loss    Draw
Japan         3       1       0
Samoa         1       3       0
Scotland      3       1       0
South Africa  3       1       0
United States 0       4       0

However some tables with duplicate rows are solvable, like this (fictional) one:
            Win    Loss    Draw
Japan         4       0       0
Samoa         0       3       1
Scotland      2       2       0
South Africa  0       3       1
United States 3       1       0

Input
Your program or function should accept 15 numbers specifying the win, loss and draw totals for each of the 5 teams. You can use any delimiter you want, input the numbers in row or column major order, and accept the numbers either via stdin or passed via an array to a function.
Because wins + losses + draws = 4, you can omit one of the values and work it out from the others if you wish, meaning that you only have to input 10 numbers.
You don't need to input any team names.
Sample input:
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0

Output
Your program or function's output should be in the form of a 5 x 5 grid printed to stdout, or an array returned from a function. Each element should specify whether the team given in the row position won, lost or drew against the team in the column position. The row ordering for the output should match the input. You can define what denotes a win, loss or draw, so the letters W, L, D or digits 0 1 2 or whatever you want can be used as long as they are clearly defined and can be distinguished from each other. Diagonal elements are undefined, you can output anything, but it should be the same in each case. Values can be separated with commas, spaces or whatever character you like, or not character. Both input and output can be formatted with all values on a single line if desired.
If a table does not have a unique solution then you must output a simple error message of your choice.
Sample output:
- W W W L
L - W D L
L L - D L
L D D - L
W W W W -

Sample output for unsolvable table:
dunno mate

This is code golf so the shortest program in bytes wins.
Pic related (Japan versus South Africa):

CJam, 57 49 47 45 bytes
{JZb:af{.*e_1+e!}:m*:e_5f/{_z2\ff-=},_,(0@?~}

This is an anonymous function that pops a two-dimensional array from the stack and leaves one in return. It contains 2 for wins, 1 for draws and 0 for losses. It also contains 1 for diagonal elements , for which you can output anything. If the problem isn't solvable, the function returns -1.
The code will work online, but it will take a while. Try it in the CJam interpreter.
Test run
$ cat input
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0
$ time cjam results.cjam < input
[1 2 2 2 0]
[0 1 2 1 0]
[0 0 1 1 0]
[0 1 1 1 0]
[2 2 2 2 1]

real    0m1.584s
user    0m4.020s
sys     0m0.146s

How it works
JZb:a e# Push 19 in base 3; wrap each digit in an array. Pushes [[2] [0] [1]].
f{    e# For each row of the input, push it and [[2] [0] [1]]; then:
  .*  e# Repeat 2, 0 and 1 (win, loss, draw) the specified number of times.
  e_  e# Flatten the resulting array.
  1+  e# Append a 1 for the diagonal.
  e!  e# Push all possible permutations.
}     e#
:m*   e# Cartesian product; push all possible combinations of permutations.
:e_   e# Flatten the results.
5f/   e# Split into rows of length 5.
{     e# Filter:
  _z  e#   Push a transposed copy of the array.
  2\  e#   Swap the result with 2.
  ff- e#   Subtract all elements from 2.
  =   e#   Check for equality.
},    e# Keep the element if `=' pushed 1.
_,(   e# Get the length of the array of solutions and subtract 1.
0@?   e# Keep the array for length 1, push 0 otherwise.
~     e# Either dump the singleton array or turn 0 into -1.

Haskell, 180 177 bytes
import Data.List
z=zipWith
m=map
a#b|(c,d)<-splitAt a b=c++[0]++d
f t=take 1[x|x<-m(z(#)[0..])$sequence$m(permutations.concat.z(flip replicate)[1,-1,0])t,transpose x==m(m(0-))x]

A win is shown as 1, a loss as -1 and a draw as 0. Diagonal elements are also 0. Unsolvable tables are empty lists, i.e. [].
Usage example: f [[3,1,0],[1,2,1],[0,3,1],[0,2,2],[4,0,0]] -> [[[0,1,1,1,-1],[-1,0,1,0,-1],[-1,-1,0,0,-1],[-1,0,0,0,-1],[1,1,1,1,0]]].
How it works: brute force! Create a list of wins/losses/draws according to the input, e.g. [3,1,0] -> [1,1,1,-1], permute, build all combinations, insert diagonals and keep all tables that are equal to their transposition with all elements negated. Take the first one.


text:
The Black Pawn's Revenge
Objective
The black pawn wants revenge. Plot out its last attack.
Rules
The black pawn (L) starts at the top row and moves downwards to the bottom row. Maximise points taken, indicating the path with X. Pawns (P) are 1, bishops (B) and knights (N) 3, rooks (R) 5, and queens (Q) 9. There won't be any kings in the input.
If there is more than one path that has the maximum amount of points, output any of those paths. There will not be any situations where the pawn cannot reach the bottom row.
Examples
Input:
----L---
-----P--
------P-
--R--P-Q
----P-P-
---P-P-P
--P-N---
-P------

Output:
----L---
-----X--
------X-
--R--P-X
----P-X-
---P-X-P
--P-X---
-P--X---

Input:
--L-----
-P------
P-------
-P------
P--Q----
-P------
P-------
-P------

Output:
--L-----
-PX-----
P-X-----
-PX-----
P--X----
-P-X----
P--X----
-P-X----

What should happen if the pawn can't reach the bottom row?

Actually, the text never says that it has to reach the bottom row. Is that the intention? Say, in the second example, would it be valid for the path to stop in the 5th row, after the pawn captured the queen?

@RetoKoradi Huh. I haven't actually thought of that. Yeah, the pawn should reach the bottom row. You can assume that any cases where the pawn can't reach the bottom row won't occur in the input.

And when it reaches the bottow row, it is promoted as a queen and kill everyone elese ...

What about El Passant?

Python, 332
def s(m,l,p):
 if not m:return 1
 b=m[0]+'-';z=filter(lambda i:(b[i]=='-')==(i==l),[l,l-1,l+1])
 if not z:return 0
 g=lambda i:s(m[1:],i,0)+[0,1,3,3,5,9]['-PBNRQ'.index(b[i])];i=max(z,key=g)
 if p:print m[0][:i]+'X'+m[0][i+1:];s(m[1:],i,p)
 return g(i)
import sys
t=sys.stdin.read().split('\n')
print t[0]
s(t[1:],t[0].index('L'),1)

Ruby 260 258 255 241 236 222
->b{s=->l,w=p{c,*x=l.map &:dup
v=[1,3,3,5,9,0]['PBNRQ'.index(c[y=w||c.index(?L)])||5]
w&&c[y]=?X
(n=x[0])?(m=[]
[y-1,y,y+1].map{|z|(z==y)^(n[z]>?.)&&m<<s[x,z]}
q,r=m.max_by{|m|m ?m[0]:0}
q&&[q+v,c+r]):[v,c]}
s[b.lines][1]}

This program defines a function (s), which, given some board rows, returns the best path as a string, and the value in points of that path. s is recursive, so at each step it evaluates all possibilities and returns the best one.
Here's an online version with tests: http://ideone.com/6eMtm4
The readable version is available here: http://ideone.com/eoXUtp
All the steps I took to reduce the size of the code can be found here.

source: Stack Exchange

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

sort: votes


text:
Seamless conversion from square to hexagon
For many games played on a grid, hexagons are the Clearly Superior Choice™. Unfortunately, many free game art sites only have seamless tile sets for square maps. On a past project, I used some of these, and manually converted them to hexagons.
However, I've gotten lazy in my old age. It should be easy to automate the process with a small script.
However, I've gotten lazy in my old age. So I'm outsourcing it to you, and disguising it as a code golf challenge1.

Input
Input is a square image in any common image format capable of 24-bit RGB color. You may also take a filename as input instead of the image data itself.
You may assume the image is square, and that the side length is a multiple of four.
Output
Output is the input tile, but converted to a hexagon (the image itself will be square, with transparent areas). You may save it to a file or display to the screen.
Again, any common image format will do. If the format you're using supports transparency, background areas must be transparent. If it doesn't, you may use color #FF00FF (that horrible fuchsia one) as a stand-in.
Method
So how do we do it? The method I use2 squashes the image a bit vertically, but overall it looks pretty good for most things. We'll do an example with this input image:

Scale: Scale the image to a 3:2 ratio. Since our images will be squares, this means you simply scale them to 75% width and 50% height. Our example input is 200x200, so we end up with this 150x100 image:

Tile: Place down copies of your scaled image in a 2x2 grid:

Crop: Grab an appropriately sized hexagon from anywhere in this 2x2 grid. Now, for ease of tiling, this hexagon isn't exactly regular. After cropping a square of the original size (here 200x200), you then crop out the corners. The crop lines should run from (roughly) the center of each left/right side to one quarter from the edge on the top/bottom:

And that's your output!
Here's an example of what it might look like when tiled (zoomed out here):

This is code golf, so shortest code in bytes wins. Standard loopholes apply, etc and so on.

1 Feel free to believe this or not.
2 Method one from this helpful site.

This question is begging for a Hexagony answer.

@sanchises Good luck.

That is where the second part of HexAgony becomes important.

-1 for saying fuchsia is horrible :P

@mbomb007 Not all fuchsia is horrible. That particular shade, used for so many old sprite sheets, makes my eyes tingle. I totally get why it's used, but...

@Geobits Any color would probably make your eyes tingle when used in place of transparency for alpha, other than black or white. I'd hate yellow and red more than fuchsia.

@mbomb007 Probably, though the #00FF00 green that's sometimes used instead isn't nearly so bad. Still, I feel like they use fuchsia more often because nobody in their right mind would want that exact color in their sprites, so it's pretty universal :P

@MartinBüttner Sorry, my laptop ran out of page file ink so I can't write new programs.

#3 - I wait on this patiently to see the cool algorithms generated... then gently and lovingly "borrow" them for my uses ;-)

Are there any requirements on how to scale the image down? Is nearest-neighbor OK?

@JanDvorak Yes, that's fine. Any common scaling technique is  adequate.

Matlab, 223 215 209 184 163 bytes
The rescaling is quite straight forward. For cropping the corners I overlay a coordinate system over the pixels, and make a mask via four linear inequalities, which determine the area of the hexagon.
l=imread(input(''));
u=size(l,1);
L=imresize(l,u*[2 3]/4);
L=[L,L;L,L];L=L(1:u,1:u,:);
[x,y]=meshgrid(1:u);
r=u/2;x=x*2;
set(imshow(L),'Al',y<x+r&y+x>r&y+x<5*r&y>x-3*r)

PS: This turned into a codegolf nim game with @MartinBüttner's submission: You alternatingly have to make your code shorter (while providing the same functionality) - the one that can make the last 'shortening' wins=)

You can save 5 bytes by changing the resize scale calculation to [k.*[2 3]/4].

Shouldn't the background areas be fuchsia, not black?

@Blackhole Thanks for letting me know, I fixed it now, even saved me quite a bunch of bytes=)

Mathematica, 231 211 209 208 201 188 173 bytes
ImageCrop[ImageCollage@{#,#,#,#},e,Left]~SetAlphaChannel~ColorNegate@Graphics[RegularPolygon@6,ImageSize->1.05e,AspectRatio->1]&@ImageResize[#,{3,2}(e=ImageDimensions@#)/4]&

This is an unnamed function which takes an image object and returns an image object:

I don't think there's a lot to explain here, but some details which are of note:

Normally, to tile an image 2x2, you'd use ImageAssemble[{{#,#},{#,#}}], i.e. you hand ImageAssemble a 2x2 matrix with copies of the image. However, there's ImageCollage which is some sort of magic function which tries to arrange a bunch of pictures as "well" as possible (whatever that means... you can even give the individual images weights and stuff). Anyway, it you give it four images of equal size and with equal (or no) weights, it will also arrange them in a 2x2 grid. That allows me to save some bytes for the nesting of the matrix, as well as the function name.
The hexagon is rendered as a single polygon via Graphics. I'm using the built-in RegularPolygon@6, but enforce an aspect ratio of 1 to stretch it as necessary. Unfortunately, Graphics needs a couple of expensive options to avoid padding and such, and it also renders black on white instead of the opposite. The result is fixed with ColorNegate and then attached to the image's original channels with SetAlphaChannel.
Graphics puts a small amount of padding around the hexagon, but we want the alpha hexagon to cover the full size of the cutout. However, SetAlphaChannel can combine images of different sizes, by centring them on top of each other and cropping to the smallest size. That means, instead of manually setting PlotRangePadding->0, we can simply scale up the hexagon image a bit with ImageSize->1.05e (and we need the `ImageSize option anyway).

HTML5 + Javascript, 562 bytes
<html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",e=>{e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=q=>{l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation="destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4,0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script>

Takes input as an image URL via textbox (the URL hopefully counts as a filename).  Outputs the data to canvas.
Version which works across all browsers (580 bytes):

<html><form><input type=text></form><canvas><script>l=document.body.children;l[0].addEventListener("submit",function(e){e.preventDefault();c=l[1].getContext("2d");i=new Image();i.onload=function(){l[1].width=l[1].height=d=i.width;c.scale(0.75,0.5);c.drawImage(i,0,0);c.drawImage(i,d,0);c.drawImage(i,0,d);c.drawImage(i,d,d);c.globalCompositeOperation = "destination-in";c.scale(1/0.75,2);c.beginPath();c.moveTo(d/4, 0);c.lineTo(d/4+d/2,0);c.lineTo(d, d/2);c.lineTo(d/4+d/2, d);c.lineTo(d/4, d);c.lineTo(0, d/2);c.closePath();c.fill();};i.src=e.target.children[0].value;})</script>

Test it with the "blocks" image from earlier via this URL: https://i.stack.imgur.com/gQAZh.png

Nice work! You could save quite a few bytes by adding id=A to the <form> and id=B to the <canvas>, then replacing l[0] with A and l[1] with B, and removing l=document.body.children;. (Works in Firefox 41; not sure which other browsers support this.) Also, I believe there are a couple of unnecessary semicolons next to right curly brackets, and a few extra spaces.

More tips: I believe you could add id=C to the <input>, then replace e.target.children[0] with C. 0.75 is equal to 3/4, 1/0.75 is equal to 4/3, d/4+d/2 is equal to d*3/4, and leading zeroes on the other decimals are not necessary. I also believe you could replace the first c.drawImage with c[p="drawImage"], then every subsequent one with c[p]; you could do the same with c.lineTo.

Python 2 + PIL, 320
Reads the name of the image file from stdin.
from PIL import ImageDraw as D,Image as I
i=I.open(raw_input())
C=A,B=i.size
i,j=i.resize((int(.75*A),B/2)),I.new('RGBA',C)
W,H=i.size
for a,b in[(0,0),(0,H),(W,0),(W,H)]:j.paste(i,(a,b,a+W,b+H))
p,d=[(0,0),(A/4,0),(0,B/2),(A/4,B),(0,B)],lambda p:D.Draw(j).polygon(p,fill=(0,)*4)
d(p)
d([(A-x,B-y)for x,y in p])
j.show()

True, sorry about that, didn't have PIL handy to try and I didn't think about it enough. I still stand by my newline statement though :P

PHP, 293 bytes
I've added some newlines for readability:
function($t){$s=imagesx($t);imagesettile($i=imagecreatetruecolor($s,$s),$t=imagescale
($t,$a=$s*3/4,$b=$s/2));imagefill($i,0,0,IMG_COLOR_TILED);$z=imagefilledpolygon;$z($i,
[0,0,$s/4,0,0,$b,$s/4,$s,0,$s],5,$f=imagecolorallocate($i,255,0,255));$z($i,[$s,0,$a,
0,$s,$b,$a,$s,$s,$s],5,$f);return$i;}

Here is the ungolfed version:
function squareToHexagon($squareImage)
{
    $size = imagesx($squareImage);
    $tileImage = imagescale($squareImage, $size * 3/4, $size/2);

    $hexagonImage = imagecreatetruecolor($size, $size);
    imagesettile($hexagonImage, $tileImage);
    imagefill($hexagonImage, 0, 0, IMG_COLOR_TILED);

    $fuchsia = imagecolorallocate($hexagonImage, 255, 0, 255);
    imagefilledpolygon(
        $hexagonImage,
        [
            0,       0,
            $size/4, 0,
            0,       $size/2,
            $size/4, $size,
            0,       $size,
        ],
        5,
        $fuchsia
    );
    imagefilledpolygon(
        $hexagonImage,
        [
            $size,       0,
            $size * 3/4, 0,
            $size,       $size/2,
            $size * 3/4, $size,
            $size,       $size,
        ],
        5,
        $fuchsia
    );

    return $hexagonImage;
}

header('Content-type: image/gif');
$squareImage = imagecreatefrompng('squareImage.png');
$hexagonImage = squareToHexagon($squareImage);
imagegif($hexagonImage);

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

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


text:
Play the elimination game
Introduction
In this challenge, your task is to simulate a certain type of elimination game.
In the game, the participants stand in a circle, and everyone is holding an integer.
On each round of the game, every participant points at the person n steps away, if n is the number they are holding. If n is positive, they count to their right, if n is negative, they count to their left, and if n is zero, they point at themselves.
Every participant who has someone pointing at them is eliminated, and leaves the circle; this ends the round.
The rounds continue until there are no participants left.
Input
Your input is a non-empty list of integers, in any reasonable format.
It represents the numbers that the participants of the game are holding.
Output
Your output is the number of rounds it takes until the game ends.
Example
Consider the input list [3,1,-2,0,8].
On the first round, the following happens:

The person holding 3 points right at the person holding 0.
The person holding 1 points right at the person holding -2.
The person holding -2 points left at the person holding 3.
The person holding 0 points at themself.
The person holding 8 points right at the person holding -2 (the list represents a circle, so it wraps around at the ends).

This means that 0, -2 and 3 are eliminated, so the second round is done with the list [1,8].
Here, 1 points at 8, and 8 points at themself, so 8 is eliminated.
The third round is done with the list [1], where 1 simply points at themself and is eliminated.
It took three rounds to eliminate all participants, so the correct output is 3.
Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test cases
[3] -> 1
[0,0,0] -> 1
[-2,-1,0,1,2,3,4,5,6,7] -> 2
[5,5,5,6,6,6] -> 2
[3,-7,-13,18,-10,8] -> 2
[-7,5,1,-5,-13,-10,9] -> 2
[4,20,19,16,8,-9,-14,-2,17,7,2,-2,10,0,18,-5,-5,20] -> 3
[11,2,7,-6,-15,-8,15,-12,-2,-8,-17,6,-6,-5,0,-20,-2,11,1] -> 4
[2,-12,-11,7,-16,9,15,-10,7,3,-17,18,6,6,13,0,18,10,-7,-1] -> 3
[18,-18,-16,-2,-19,1,-9,-18,2,1,6,-15,12,3,-10,8,-3,7,-4,-11,5,-15,17,17,-20,11,-13,9,15] -> 6

Are you sure about the last test case, I get 5?

@flawr I can check my reference implementation in about an hour (had to leave my computer), but it should be correct.

Just to be clear: n is the number the person is holding?

@PeterTaylor Yes, it is. I'll clarify that later in the challenge.

Pyth, 15 bytes
f!=.DQ.e%+bklQQ

Test suite thanks to kirby
Uses the same iteration mechanism as @orlp, but detects the number of iterations using f, the "Repeat until falsy" function, to detect the [] once we're done.

Matlab, 91 77 bytes
function k=f(a);k=0;while a*0+1;l=numel(a);a(mod((1:l)+a-1,l)+1)=[];k=k+1;end

Old version:
function k=f(a);for k=1:numel(a);a(mod((1:l)+a-1,l)+1)=[];l=numel(a);if l==0;break;end;end

This is a challenge where matlab shines, the heart of this code is the deletion of the array entries: a(mod((1:l)+a-1,l)+1)=[] which is quite elegant I think.

CJam, 21 bytes
q~{__ee{~+0t}/0-}h],(

Test suite.
Takes input as a CJam style list, but the test suite takes care of the conversion from the format in the challenge.
Explanation
q~     e# Read and evaluate the input.
{      e# While the array is non-empty...
  _    e#   Copy the array. The original is left on the stack so that we can use the
       e#   stack depth to count the number of iterations later.
  _ee  e#   Make another copy and enumerate it, which means that each element is replaced
       e#   by a pair containing the element and its index in the array.
  {    e#   For each such pair...
    ~+ e#     Add the value to the index, giving the index it points at.
    0t e#     Set the value in the original array at the pointed-at index to 0.
       e#     This works without giving false positives because all 0s point to themselves.
  }/
  0-   e#   Remove all 0s from the array.
}h
],(    e# Wrap the stack in an array, get its length and decrement it to determine how
       e# many iterations this process took.

Thanks: ee is almost exactly what I was looking for yesterday for a different question.

C#, 251 219 211 197 193 bytes
The most ungolfable non-esoteric language strikes again.
using System.Linq;class X{static void Main(string[]a){int i=0,c;for(;(c=a.Length)>0;i++)a=a.Where((e,x)=>!a.Where((f,y)=>((int.Parse(f)+y)%c+c)%c==x).Any()).ToArray();System.Console.Write(i);}}

This program expects the input sequence as command-line arguments. For example, to input the list [5,5,5,6,6,6], call it with command-line arguments 5 5 5 6 6 6.
Thanks to Martin Büttner for some tips.
Golfed it to 197 by realizing that I can reuse the args array even though it’s an array of strings. I only need to parse them into an integer in one place.
Golfed to 193 by realizing that .Where(...==x).Any() is shorter than .Select(...).Contains(x).
Ungolfed
using System.Linq;
class X
{
    static void Main(string[] args)
    {
        var iterations = 0, count;

        // In the golfed version, this is a `for` loop instead.
        while ((count = args.Length) > 0)
        {
            // Create a new args array containing the items to be kept.
            args = args.Where((item, index) =>
            {
                // Should the item at index `index` be deleted?
                var deleteThisIndex = args.Where((item2, index2) =>
                    // Modulo that works with negative numbers...
                    ((int.Parse(item2) + index2) % count + count) % count
                        == index);

                return !deleteThisIndex.Any();

            }).ToArray();

            iterations++;
        }

        System.Console.Write(iterations);
    }
}

C# is the most ungolfable? Surely you must be mistaken; everyone knows that's Java. :P

@AlexA. Pfft, I'm with Timwi on this one. I've beaten C# with Java plenty of times :P

You're wrong, Pyth or CJam are the most ungolfable, C# is the most unwinnable language!

Pyth, 17 bytes
tl.u.DN.e%+kblNNQ

Coincidentally very similar to kirbyfan's answer.

Mathematica, 71 bytes
Length@FixedPointList[#~Delete~Mod[Plus~MapIndexed~#,Length@#,1]&,#]-2&

67: (i=0;#//.l:{__}:>l~Delete~Mod[++i;Plus~MapIndexed~l,Length@l,1];i)&

The Plus~MapIndexed~# is really clever, but I wonder if there isn't a shorter way using l+Range@Length@l.

R, 105 bytes
code
l=scan();o=c();z=0;while((n=length(l))>0){for(i in 1:n)o=c(o,(i+l[i]-1)%%n+1);l=l[-o];o=c();z=z+1};cat(z)

ungolfed
l <- scan()                  # get input as a 'l' vector from user
o <- c()                     # create a empty vector
z=0                          # create a counter starting at 0
while((n=length(l))>0){      # while the length of the input is more than 0
  for(i in 1:n){             # iterate through the vector
    o=c(o,(i+l[i]-1)%%n+1)   # add the index that will be deleted to the 'o' vector
  }
  l=l[-o]                    # remove the 'o' vector indexes from 'l'
  o=c()                      # empty 'o'
  z=z+1                      # add 1 to counter
}
cat(z)                       # print the counter

Pyth, 21 bytes
lt.u@LN-UlN.e%+kblNNQ

Live demo with test cases.

Ruby, 78 74 bytes
f=->a{b,i=[],0;(a.map{|e|b<<a[(e+i)%a.size]};a-=b;i+=1)while a.size>0;p i}

awk, 66 bytes
{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r

Simply uses mod length array to keep it inside the array. In the input the numbers need to be separated by spaces.
Usage example
echo "-2 -1 0 1 2 3 4 5 6 7" | awk '{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r'

Here's all the input examples in the appropriate format

3
0 0 0
-2 -1 0 1 2 3 4 5 6 7
5 5 5 6 6 6
3 -7 -13 18 -10 8
-7 5 1 -5 -13 -10 9
4 20 19 16 8 -9 -14 -2 17 7 2 -2 10 0 18 -5 -5 20
11 2 7 -6 -15 -8 15 -12 -2 -8 -17 6 -6 -5 0 -20 -2 11 1
2 -12 -11 7 -16 9 15 -10 7 3 -17 18 6 6 13 0 18 10 -7 -1
18 -18 -16 -2 -19 1 -9 -18 2 1 6 -15 12 3 -10 8 -3 7 -4 -11 5 -15 17 17 -20 11 -13 9 15

STATA, 146 bytes
inf a using a.
gl b=0
qui while _N>0{
g q$b=0
g c$b=mod(_n+a-1,_N)+1
forv y=1/`=_N'{
replace q$b=1 if _n==c$b[`y']
}
drop if q$b
gl b=$b+1
}
di $b

Uses the paid version of STATA. Assumes the input is in a newline separated file called a.. Limited to situations where no more than 1023 rounds are required due to a maximum number of variables allowed (can be fixed at the cost of 10 bytes). It reads the data and runs a loop until there are no more observations. In each iteration, make a variable with the value of the index it points to. For each observation, if another observation points to it, set an indicator to drop the variable. Then drop all observations with that indicator and increment the counter. After the loop, print the counter.

Python 2, 122 bytes
def f(l):
 if not l:return 0
 L=len(l);x=[1]*L
 for i in range(L):x[(i+l[i])%L]=0
 return 1+e([v for i,v in zip(x,l)if i])


text:
Minifying math statements
The Challenge
You are the owner of an amazing service called Coyote Beta, which magically answers math questions its users send to it over the internet.
But it turns out, bandwidth is expensive.  You have two choices, either create a "Coyote Beta Pro" or find some way to solve this.  Just recently, someone queried (x + 2). Couldn't the client send x+2, and the user would see no difference?
The Task
Your task is to "minify" math expressions.  Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input.  The parentheses around associative operations need not be preserved.
The only operators given here are +, -, *, /, and ^ (exponentiation), with standard mathematical associativity and precedence.  The only whitespace given in the input will be actual space characters.
Sample Input/Output
Input       | Output
------------|--------------
(2+x) + 3   | 2+x+3
((4+5))*x   | (4+5)*x
z^(x+42)    | z^(x+42)
x - ((y)+2) | x-(y+2)
(z - y) - x | z-y-x
x^(y^2)     | x^y^2
x^2 / z     | x^2/z
- (x + 5)+3 | -(x+5)+3

Scoring
Input/output can use any preferred method.  The smallest program in bytes wins.
Exact bits
Exponentiation is right associative and also follows standard math precedence (being the highest).  A valid numeric literal is /[0-9]+/, and a valid variable literal is /[a-z]+/.  A single variable literal represents a single value even when its character length is longer than 1.
What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged.

The idea is to create a minimal equivalent statement that results in the same parse tree.  This is so that Coyote Beta can display it visually when the user makes a query.

If a valid variable is /[a-z]+/, that means multiplication by juxtaposition like ab is disallowed?

Yeah, ab means the single value ab, not a*b.  This is so people can focus on the core problem instead of implementing a bunch of features in their parser.

Need unary plus be supported?

Or unary minus?

No, that's not necessary.  Unary minus is, however.

You do want 2+(3+4) to be changed to 2+3+4, right? This does change the parse tree.

Yeah, what I said in the first comment wasn't specific enough.  I should say it results in an "equivalent" parse tree, where "equivalent" means "the same parse tree, plus any rearrangements to associative operations".

Why not Rhenium Beta?

I take issue with the claim that x^(y/2)=x^y/2; exponentiation has a higher order precedence, ergo, x^y/2=(x^y)/2.

As far as I'm aware, x^(y/2)=x^y/2 is never stated in the problem.  If it is, it's an error an should be fixed, but I can't find it.

Oh, was Conor's statement in response to a deleted comment?

Are we permitted to simplify?

What is the correct output for a+(-b+c)?  Is it a-b+c or a+(-b)+c?

You're not permitted to simplify beyond associative operator rearrangement.

The correct output for a+(-b+c) is either a+(-b)+c or a+(-b+c).  It's interesting that that input has two minimal solutions.  Anyway, a-b+c can't be the correct answer because instead of using the unary -, it's using the binary -.

@TND - a+(-b+c) cannot be the correct output as the parentheses around associative operations must be removed.

Yes, why wouldn't the answer be a+-b+c ?

Yeah, it makes more sense to do it that way.  I was worried if I said a string with two operators consecutively like that was a possible input, it would throw off the parsers of anyone who was already solving it.

Aww man, I was going to submit Prompt X:expr(X) in TI-BASIC but you can't simplify :(

Surely if truly optimal minification was the objective, you'd want some basic algebraic simplifications like --a⇒a, a-(b-c)⇒a-b+c, a/(b/c)⇒a/b*c, a*b+a*c+a*d⇒a*(b+c+d)?

C#, 523 519 504 bytes
Check the in-code comments to see how it works!

Golfed
using System;using System.Collections.Generic;namespace n{class p{static void Main(string[]a){foreach(String s in a){String r=s.Replace(" ","");List<int>l=new List<int>();for(int i=0;i<r.Length;i++){if(r[i]=='('){l.Add(i);continue;}if(r[i]==')'){switch(r[Math.Max(l[l.Count-1]-1,0)]){case'+':case'(':switch(r[Math.Min(i+1,r.Length-1)]){case'+':case'-':case')':r=r.Remove(Math.Max(l[l.Count-1],0),1);r=r.Remove(Math.Min(i,r.Length)-1,1);i-=2;break;}break;}l.RemoveAt(l.Count-1);}}Console.WriteLine(r);}}}}

Ungolfed
using System;
using System.Collections.Generic;

namespace n {
    class p {
        static void Main( string[] a ) {
            // Loop every String given for the program
            foreach (String s in a) {
                // Get rid of the spaces
                String r = s.Replace( " ", "" );

                // A little helper that will have the indexes of the '('
                List<int> l = new List<int>();

                // Begin the optimizatio process
                for (int i = 0; i < r.Length; i++) {
                    // If char is an '(', add the index to the helper list and continue
                    if (r[ i ] == '(') {
                        l.Add( i );
                        continue;
                    }

                    // If the char is an ')', validate the group
                    if (r[ i ] == ')') {
                        // If the char before the last '(' is an '+' or '(' ...
                        switch (r[ Math.Max( l[ l.Count - 1 ] - 1, 0 ) ]) {
                            case '+':
                            case '(':
                                // ... and the char after the ')' we're checking now is an '+', '-' or ')' ...
                                switch (r[ Math.Min( i + 1, r.Length - 1 ) ]) {
                                    case '+':
                                    case '-':
                                    case ')':
                                        // Remove the '()' since they're most likely desnecessary.
                                        r = r.Remove( Math.Max( l[ l.Count - 1 ], 0 ), 1 );
                                        r = r.Remove( Math.Min( i, r.Length ) - 1, 1 );

                                        // Go two steps back in the loop since we removed 2 chars from the String,
                                        //   otherwise we would miss some invalid inputs
                                        i -= 2;
                                        break;
                                }

                                break;
                        }

                        // Remove the last inserted index of '(' from the list,
                        //   since we matched an ')' for it.
                        l.RemoveAt( l.Count - 1 );
                    }
                }

                // Print the result
                Console.WriteLine( r );
            }
        }
    }
}

Side notes

Fixed some typos and renamed some vars.
Nested an switch to get rid of an unnecessary variable. Also, fixed a bug that would render some solutions invalid, reported by Anders Kaseorg.

P.S.: If you have a tip or found a bug, please let me know in the comments and I'll try to fix it ( I'll then add a note about the bug fix with your name ;) )

Nice answer! :D substantial answers here are generally better recieved if you include an explanation :P

Can I do it in the form of code comments?

Sure, whatever works c:

Then I'll do that! I'll also try to add a summary somewhere.

Welcome to Programming Puzzles and Code Golf, by the way! (even though it's not your first answer)

You can’t return r; from void Main(). Also, with that fixed, ((4+5))*x gives the wrong answer 4+5*x.

@AndersKaseorg Thanks for finding out the bug!If I may ask you a question, do you know why the code hasn't is methods and classes coloured as it has in SO? Is it an error I made or that doesn't happen here? EDIT! Nevermind, found out how to do it.

Test your answer on at least the provided cases; it still doesn’t pass them all.

The only test from those that have been supplied that fails is the x^(y^2) that doesn't parse the (). I'm still figuring out how to do it without expanding too much the code.

C++, 284 bytes
Golfed
#include<iostream>
#include<algorithm>
int main(){std::string e;std::getline(std::cin,e);e.erase(std::remove_if(e.begin(),e.end(),isspace),e.end());for(int x=0;x<e.length();x++){if(e[x]=='('&&e[x+1]=='('){e.erase(x,1);}if(e[x]==')'&&e[x+1]==')'){e.erase(x,1);}}std::cout<<e;return 0;}

Ungolfed
#include<iostream>
#include<algorithm>

int main()
{
    std::string e;
    std::getline(std::cin, e);
    e.erase(std::remove_if(e.begin(), e.end(), isspace), e.end());
    for(int x = 0; x < e.length(); x++) {
        if (e[x] == '(' && e[x+1] == '('){
            e.erase(x, 1);
        }
        if (e[x] == ')' && e[x+1] == ')'){
            e.erase(x, 1);
        }
    }
    std::cout<<e;
    return 0;
}

This doesn’t have any precedence logic and fails many of the given test cases.


text:
Golf Me An OOP!
Golf Me An OOP!
Two important components of object-oriented programming are inheritance and composition. Together, they allow for creating simple yet powerful class hierarchies to solve problems. Your task is to parse a series of statements about a class hierarchy, and answer questions about the hierarchy.
Input
A series of statements and questions about a class hierarchy, read from a file or standard input, whichever is best for your language. If you use the file option, the filename will be passed as the first argument to your code (function argument or command line argument, whichever you choose). The format is as follows:
<statement> : <name> is a <name>. | <name> has a <name>.
<question> : Is <name> a <name>? | Does <name> have a <name>?
<name> : a-z | A-Z | sequence of alphanumerics or underscores, starting with a letter

The input will always be statements, then questions. All class names will begin with an uppercase English letter (A-Z), and all member names will begin with a lowercase English letter (a-z). All names are case-sensitive - ABC123 is not the same class as Abc123.
There will not be any cyclical inheritance - if B inherits from A, A will not inherit from B or any of B's children.
Only class names will be a part of a hierarchy - statements such as foo is a bar. or document has a name. will not occur.
Output
A series of truthy or falsey values, as answers to the queries, written to standard output or as the return value of your function. If you do not have enough information to answer a question (e.g. questions that involve names you have not seen in the statements), answer with a falsey value.
Test Cases
Case 1:
Input:
B is a A.
C is a B.
A has a foo.
Does B have a foo?
Is C a A?
Is D a A?

Output:
True
True
False

Case 2:
Input:
Cop is a Person.
Criminal is a Person.
Sheriff is a Cop.
Crooked_Cop is a Cop.
Crooked_Cop is a Criminal.
BankRobber is a Criminal.
Cop has a badge.
Criminal has a criminal_record.
Person has a name.
Is Crooked_Cop a Person?
Does Criminal have a name?
Is Crooked_Cop a BankRobber?
Does Person have a potato?
Is Cop a Cop?

Output:
True
True
False
False
True

Rules

You may answer with a function or a program
Standard loopholes are forbidden
This is code-golf, so shortest correct answer in bytes wins
The winning answer will be chosen in one week

Good luck, and may the OOP be with you!
Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

How is Does Criminal have a name? equal to True? Do all objects have a name?

@JAtkin Criminal is a Person. Person has a name.

Ahh... I had missed that.

Do I need to take all the input at once, or can I take it line by line like a interactive console? If #2, can I output a truthy\falsey even if the input is a statment?

@JAtkin All at once or line-by-line, your choice. If it's a statement, there shouldn't be any output. Only questions get answers.

Would a potato have a potato?

@Candles Composition and inheritance do not apply to objects.

Just a note: these questions do not have truth value, so rather than true/false, the answers should be yes/no.

CJam, 59 bytes
q_'.e=\N/{)'?=\S/>_,(%}%/(__,*{(2$z~@f=.*\m*|}/ff{1$e=>:=N}

This finishes instantly for both test cases.
It either prints the second name name of the question or 1 (both truthy), or 0 (falsy).
Try it online in the CJam interpreter.
Idea
Because of the distinction between classes and members, the challenge boils down to creating a preorder for which the input provides a partial definition.
We define that x ≺ y iff x is a y or x has a y.
For the first test case, the input states that B ≺ A, C ≺ B and A ≺ foo. Because of transitivity, we also have B ≺ foo, C ≺ A and A ≺ foo. Also, because of reflexivity, x ≺ x is always true.
For a given input, we thus can extract the partial definition of ≺ from the statements, apply transitivity a sufficient amount of times to complete the definition of ≺ and finally answer the questions.
Code
q_     e# Push all input from STDIN and a copy.
'.e=   e# Count the number of dots/statements (C).
\N/    e# Split the original input at linefeeds.
{      e# For each line:
  )'?= e#   Pop the last character and check if it is a question mark.
       e#   Pushes 1 for '?', 0 for '.'.
  \S/  e#   Split the modified line at spaces.
  >    e#   Remove the first chunk ("Does" or "Is") for questions.
  _,(% e#   Keep the first and last element of the resulting array.
}%/    e# Split the line array into chunks of length C.
(_     e# Extract the first chunk (statements) and push a copy.
       e# The original becomes an accumulator for ≺.
_,*    e# Repeat the statements C times.
{      e# For each of the repeated statements:
  (    e#   Shift out the first name.
       e#     ["w" "x"] -> ["x"] "w"
  2$z~ e#   Copy the accumulator, zip it and dump.
       e#     [["x" "y"] ["z" "w"]] -> ["x" "z"] ["y" "w"]
  @f=  e#   Rotate the shifted out name on top and check for equality.
       e#     ["y" "w"] "w" -> [0 1]
  .*   e#   Vectorized string repetition.
       e#     ["x" "z"] [0 1] -> ["" "z"]
  \m*  e#   Swap the result with the shifted array and apply Cartesian product.
       e#     ["" "z"] ["x"] -> [["" "x"] ["z" "x"]]
       e#   This accounts for transitivity; we had ["w" "x"] and ["z" "w"],
       e#   so now we have ["z" "x"].
  |    e#   Perform set union with the accumulator to add the new pairs.
}/     e#
ff{    e# For each of the questions on the bottom of the stack.
  1$e= e#   Count the occurrences of the question pair in the accumulator.
  >    e#   Remove 0 or 1 elements from the question pair.
  :=   e#   Check for equality.
       e#   If the question pair occurs in the accumulator, this pushes the
       e#   second name of the question pair. Otherwise, it pushes 1 if the
       e#   names are equal (to account for reflexivity) and 0 otherwise.
  N    e#   Push a linefeed.
}      e#

This is impressive considering that CJam doesn't have classes :D

This is beautiful.

@BetaDecay Classes are essentially nested sets; classes are implemented in every language. Say in the first example. C:{B:{A:{foo:{}}}}

Python 3, 431 331 308 bytes
o={}
f={}
def h(z,f):
 if z not in o:f[z]=[z];o[z]=[]
while 1:
 g=input().split(' ');r=2;l=g[-1][:-1]
 if'.'in g[3]:
  if'i'in g[1]:h(g[0],f);h(l,f);f[g[0]]+=f[l]
  if'h'in g[1]:o[g[0]]+=l,
 else:
  if'I'in g[0]:r=any(l in z for z in f[g[1]])
  if'D'in g[0]:r=any(l in o[z] for z in f[g[1]])
 if r<2:print(r)

This is the full version with comments
objects = {}
synonyms = {}

def createObject(name):
    """
    Create a object with `name` if is does not yet exist and start a synonym tree.
    """
    if name not in objects:
        synonyms[name] = [name]
        objects[name] = []

# use this to read from a file
# with open("questions.txt") as file:
#     for l in file:
        # print(">>> " + l, end='')
        # inArg = l.replace("\n","").split(" ")

while True: # to read from a file comment this
        inArg = input(">>> ").split(" ") # and this out

        out = -1

        if '.' in inArg[3]: # statement
            last = inArg[3].replace('.','')

            if 'i' in inArg[1]: # is a
                createObject(inArg[0])
                createObject(last)
                synonyms[inArg[0]] += synonyms[last]

            if 'h' in inArg[1]: # has a
                objects[inArg[0]] += [last]

        else:# question
            last = inArg[-1].replace('?','')

            createObject(inArg[1])
            if 'I'in inArg[0]: # Is a
                out = any([last in syn for syn in synonyms[inArg[1]]])

            if 'D'in inArg[0]: # Does have a
                out = any(last in objects[syn] for syn in synonyms[inArg[1]])

        if out != -1:
            print(out)

Output for test case #1:
True
True
False

Case #2:
True
True
False
False
True

I removed the debug commands for clarity in the main program, but if you would like to see them just look in the history

Instead of using global f in h(z), use def h(z,f) and pass the global f in when calling it. In fact, you don't need h(z) at all - just put the body where you call it. You don't need r=2, and you can just do print(r) without the if, since you need to output a falsey value for false queries. You can rename syn to z and shave off several bytes there. I don't think you need the [] around your list comprehension in the first any.

You also use e once, so you can do away with the definition and just use [a,b,c,d]. Instead of if s(i,g) is not None, do if s(i,g) - re.Match objects are always evaluated to True if a match is found. You can also drop 2 bytes with f[x]+=f[y].

@Mego Wow, thanks for all the tips. I'll need to put them in later.

This post will probably help you out a lot

@Mego Big thanks, its down to 396 now. I will post is shortly.

@Mego I had a little more fun and added debugging tools to the ungolfed version ;)

JavaScript, 265 263 bytes
for(o={};i=prompt().split(/\W/);)a=i[0],b=i[1],d=i[2],b=="is"?((o[a]=o[a]||{p:[],k:{}}).p.push(d),o[d]=o[d]||{p:[],k:{}}):b=="has"?o[a].k[d]=1:alert(o[b]&&(a>"E"?b==d|(c=n=>~(p=o[n].p).indexOf(d)|p.some(c))(b):(c=n=>o[n].k.hasOwnProperty(i[4])|o[n].p.some(c))(b)))

Enter a blank string to quit.
Explanation
for(
  o={};                               // o = all objects
  i=prompt().split(/\W/);             // i = command as an array of words
)
  a=i[0],                             // a = first word
  b=i[1],                             // b = second word
  //c=i[2],                           // c = third word
  d=i[3],                             // b = fourth word
  //e=i[4],                           // e = fifth word

  // Case: <name> is a <name>.
  b=="is"?(
    (o[a]=o[a]||{p:[],k:{}})          // create the object if it does not exist
      .p.push(d),                     // add the parent to the object's list of parents
    o[d]=o[d]||{p:[],k:{}}            // create the parent if it does not exist
  ):

  // Case: <name> has a <name>.
  b=="has"?
    o[a].k[d]=1                       // set the specified property

  :
  alert(                              // display the responses to the questions
    o[b]                              // false if the queried object does not exist
    &&(

      // Case: Is <name> a <name>?
      a>"E"?                          // "Is" > "E" and "Does" < "E"
        b==d                          // check if it is itself
        |(c=n=>
          ~(p=o[n].p)                 // p = direct parents of current object
            .indexOf(d)               // check direct parents for the object
          |p.some(c)                  // check the grandparents
        )(b)

      // Case: Does <name> have a <name>?
      :
        (c=n=>
          o[n].k.hasOwnProperty(i[4]) // check if this object has the property
          |o[n].p.some(c)             // check it's parents for the property also
        )(b)
    )
  )

Could you use string.split(" ");?

@JAtkin I used .match(/\w+/g) to remove the punctuation from the words.

I saw that, but wouldn't .split(" ") be shorter or am I missing something? (I don't know javascript)

@JAtkin If I used .split I would also have to use .slice(0,-1) (twice) because B is a A. would make B inherit A. (with the .).

@JAtkin Actually I just found out that split accepts regular expressions so I could use .split(/\W/). Thanks for causing me to look that up!

Ahh, interesting.

Haskell, 157 bytes
o s=v(x 0#k)#(x 1#q)where(k,q)=break((=='?').l.l)(words#lines s)
x n w=(w!!n,init$l w)
v k(a,c)=a==c||or[v k(b,c)|b<-snd#(filter((==a).fst)k)]
(#)=map
l=last

Give the string to o. Not sure if making x and v ('extract' and 'verify') infixes cuts more than making map an infix, or if both is possible.
EDIT: Explanation
So, (#) is how you define an infix operator, I use it just as a shorthand for map, applying a function to each element of a list. Resolving this and the other alias l, avoiding the 'direct-function-application'-operator $ and adding even more parentheses and spacing things out, and with real function names we arrive at:
oop string = map (verify (map (extract 0) knowledge)) (map (extract 1) questions)
 where (knowledge,questions) = break ((=='?').last.last) (map words (lines string))

extract n wordlist = (wordlist!!n,init (last wordlist))

verify knowledge (a,c) = (a==c)
               || or [verify knowledge (b,c) | b <- map snd (filter ((==a).fst) knowledge)]

map words (lines string) is a list of word lists of each lines in the input string.
(=='?').last.last is a predicate indicating whether the last letter in the last word of a line is a question mark, i.e. whether the line is a question.
break breaks the list in a tuple of the first part without questions (all statements) and the part from the first question on (all questions).
mapping extract n on these takes out of each word list the elements we really want, the nth one (which in statements is the first word - so n == 0, and in questions is the second word - so n == 1) using the !! operator and the last one, from which we have to cut the last letter (either '.' or '?') using init.
(Note that I completetely ignore capitalization, that's because I completely ignore the distinction between classes and members, members are just leafs of a tree constructed by the knowledge base (but not all leafs represent members, they may also be classes with neither subclasses nor members), in which every child node represents a subclass or member of what its parent node represents. I JUST REALIZED THIS IS A WRONG THING TO DO in cases not covered by OP. Will edit solution soon.)
Now, map (extract 0) knowledge and map (extract 1) questions are lists of tuples of names representing a subclass- or member-relationship of the first to the second.
The tuples in map (extract 0) knowledge are all true relationships, those in map (extract 1) questions are now mapped the verify function over, with the first argument set to map (extract 0) knowledge.
(From now on, inside verify, knowledge is a parameter name and refers to the already extracted tuple list.)
(Also, when reading verify, note that while the || (after the inelegant linebreak to avoid horizontal-scroll on SE) is a normal boolean disjunction between the 'reflexive' and the 'recursive' case, or folds that over a list, i.e. checks if any list element is true.)
Now, a relations is obviously correct if it is reflexive. Strictly speaking, no, a potato does not have a potato (and it isn't even one in the sense 'is' is used here, as in 'A Cop is a Cop'), but that's just the termination condition that covers all relationships after walking down the tree (which unlike in the case of real trees means 'towards the leafs').
In all other cases, we try to take a tuple from knowledge (after we filtered to make sure we 'see' only pairs with the same first element as that we want to check), and go on from where it points to. The list comprehension deals with all possible tuple to continue with and calls verify again in each case. A dead end will just have an empty list here and return false overall, and so not influence the instance of verify it was called by.

Could you add a short explanation for non haskell fluent people?

Happily! I just don't do it for every post until requested.

Ok, thanks! (filler)

Wow, that's some explanation.

This is a bit over my head, but thank you for posting an explanation anyway!

Which parts confuse you? Does the level of detail decrease during the explanation, as I see it?

It's not an issue, don't worry about it. Some of the terms are unfamiliar to me (I'll look them up later), and my lack of knowledge of haskell/functional programming concepts all kinda add up to this being over my head (plus I'm only 16).

I just finished reading the first half of Learn you a haskell for great good! and this now I understand this! (This answer is actually what prompted me to learn more about haskell and FP, and it is sooooo cool!)

Glad you spent the holidays in a more productive way than I did (easy) and that you are already that enthusiastic about programming languages and theory! Happy to help :)


text:
Koopa Shell Sequence
In various Super Mario games green and red Koopa Troopa shells can slide frictionlessly on flat surfaces and destroy brick blocks that are in their way. When a shell hits a brick block the block breaks, turning it into empty space, and the Koopa shell reverses direction. As an example, watch the red shell here.
Suppose a Super Mario level is just one block high and every grid cell is either a brick or empty space, except for the leftmost cell which contains a rightward moving shell. The level is also periodic, so if the shell exits the right or left edge of the level it will reenter on the opposite side. In this situation the shell will continue to bounce off of and break all the brick blocks in the level until there are no more. How far will the shell have traveled just after the last brick block is broken?
Challenge
Write a program or function that takes in a non-negative decimal integer. This number, expressed in binary with no leading zeros (the only exception is 0 itself), encodes the one-block-high level layout. A 1 is a brick block and a 0 is empty space.
The Koopa Shell is inserted at the very left edge of the level and is initially moving right. For example, the level associated with input 39 is
>100111

because 100111 is 39 in binary, and > and < represent right and left moving shells respectively.
You need to print or return the total distance traveled by the shell once the very last brick block (a.k.a. 1) has been broken.
The output for 39 is 7 and the changes in the level look like this:
Level      Cumulative Distance
>100111    0
<000111    0
>000110    0
0>00110    1
00>0110    2
000>110    3
000<010    3
00<0010    4
0<00010    5
<000010    6
000001<    7
000000>    7  <-- output

Similarly, the output for 6 is 1:
Level    Cumulative Distance
>110     0
<010     0
001<     1
000>     1  <-- output

The shortest code in bytes wins.
For reference, here are the outputs for inputs 0 to 20:
0 0
1 0
2 0
3 0
4 0
5 0
6 1
7 1
8 0
9 0
10 1
11 2
12 2
13 1
14 3
15 3
16 0
17 0
18 1
19 3
20 2

And here are the outputs up to input 1000.

CJam, 29 26 24 bytes
Thanks to Sp3000 for saving 3 bytes.
q~2b{_1&}{W\({%}*0+}w],(

Test suite. (This prints all results from 0 to the integer given on STDIN.)
Explanation
This turns the spec on its head a bit: instead of moving the shell through the binary string, we shift and reverse the binary string such that the shell is always at the front, pointing to the right:
q~      e# Read and evaluate the input.
2b      e# Convert to base-2 to get the "level".
{_1&}{  e# While there is a 1 in the level...
  W\    e#   Put a -1 below the level.
  (     e#   Pull off the first digit, i.e. the cell the shell is pointing at.
  {     e#   If it's a 1 (i.e. a brick)...
    %   e#     Reverse the level, consuming the -1. This isequivalent to reversing the
        e#     shell in place.
  }*
  0+    e#   Append a zero. If the cell was a brick, this just replaces it with an empty
        e#   cell. Otherwise, this rotates the level by one cell. This is equivalent
        e#   to moving the shell one cell through the periodic level.
        e#   Note that if the leading cell was 0, the -1 remains on the stack.
}w
],(     e# Wrap the stack in an array, get its length and decrement.

Pyth, 24 bytes
&.WsH_XZeaYxZ1 0jQ2ssPBY

Try it online: Demonstration or Test Suite
The following 22 bytes code should also do the trick. It doesn't work currently, due to a bug in the Pyth compiler.
&u_XGeaYxG1ZjQ2)ssPBPY

edit: Bug fixed, but of course the solution doesn't count.
Try it online: Demonstration or Test Suite
Explanation:
Alternating from the front and the back I do the following:

I search for a 1
Remember this index by putting it in a list
Update this 1 to a 0

When there are no 1s left, I calculate the distance. Important is: The shell moves each distance in the list twice (forward and backward), except the last distance.
&.WsH_XZeaYxZ1 0jQ2ssPBY   implicit: Y = empty list
                jQ2        convert input number to binary
 .WsH                      start with Z=^;
                           while the sum(Z) > 0, apply the the following to Z:
           xZ1                index of 1 in Z
         aY                   append this to Y
        e                     take the last element of Y (=this index)
      XZ       0              set this 1 (at index ^) in Z to 0
     _                        and revert the order of Z
                           this returns a list of zeros
&                          don't print ^, print the next thing
                     PBY   creates the list [Y, Y[:-1]]
                    s      combine these lists
                   s       sum up the distances