# TDD练习题

www.MyException.Cn  网友分享于：2013-10-31  浏览：14次
TDD练习

```public class DeliverTest {
@Test
public void onePlayer() throws Exception {
Deliver deliver = new Deliver(1);
assertArrayEquals(new int[]{1}, deliver.play(2));
assertArrayEquals(new int[]{1}, deliver.play(-1));
}

@Test
public void twoPlayers() throws Exception {
Deliver deliver = new Deliver(2);
assertArrayEquals(new int[]{2, 1}, deliver.play(2));
assertArrayEquals(new int[]{1,2},deliver.play(1));
}

@Test
public void manyPlayers() throws Exception {
Deliver deliver=new Deliver(20);
System.out.println(Arrays.toString(deliver.play(3)));
}
}
```

代码：

```public class Deliver {
public static final int FIRST_PLAYER = 0;
public static final int FIRST_NUMBER = 1;
private int[] evicted;
private int evictPos;
private int repeat;
private int[] players;
private int current;

public Deliver(int count) {
evicted = new int[count];
}

private void reInit(int repeat) {
evictPos = 0;
this.repeat = repeat;
players = createPlayers();
current = FIRST_PLAYER;
}

private int[] createPlayers() {
int count = evicted.length;
int[] players = new int[count];
for (int k = 0; k < count; k++)
players[k] = k + FIRST_NUMBER;
return players;
}

public int[] play(int repeat) {
reInit(repeat);
replay();
return evicted;
}

private void replay() {
talk(FIRST_NUMBER);
}

private void talk(int numberOff) {
if (shouldEvict(numberOff)) {
evict();
return;
}
deliver(numberOff);
}

private boolean shouldEvict(int numberOff) {
return numberOff >= repeat;
}

private void evict() {
evicted[evictPos++] = players[current];
if (isOnePlayerOnly())
return;
players = remove(current);
replay();
}

private boolean isOnePlayerOnly() {
return players.length == 1;
}

private int[] remove(int index) {
int[] remaining = new int[players.length - 1];
int next = index + 1;
System.arraycopy(players, FIRST_PLAYER, remaining, FIRST_PLAYER, index);
System.arraycopy(players, next, remaining, index, players.length - next);
return remaining;
}

private void deliver(int numberOff) {
current = nextPlayer();
talk(numberOff + 1);
}

private int nextPlayer() {
int next = current + 1;
return next >= players.length ? FIRST_PLAYER : next;
}

}
```

1 楼 抛出异常的爱 2011-06-03

```@Test
public void manyPlayers() throws Exception {
Deliver deliver=new Deliver(20);
System.out.println(Arrays.toString(deliver.play(3)));
} ```

2 楼 william_ai 2011-06-03

3 楼 oray2011 2011-06-03

```@Test
public void manyPlayers() throws Exception {
Deliver deliver=new Deliver(20);
System.out.println(Arrays.toString(deliver.play(3)));
} ```