Skip to content

Instantly share code, notes, and snippets.

@ngzhian
Created April 28, 2014 14:19
Show Gist options
  • Save ngzhian/11373536 to your computer and use it in GitHub Desktop.
Save ngzhian/11373536 to your computer and use it in GitHub Desktop.
An experiment to see how sorting Scissors Paper Stone (objects with circular ordering) will work out
import java.util.Collections;
import java.util.List;
import java.util.Vector;
public class ScissorsPaperStoneSortExpt {
public static void main(String[] args) {
List<Move> list = new Vector<Move>();
list.add(Move.paper());
list.add(Move.scissors());
list.add(Move.scissors());
list.add(Move.stone());
list.add(Move.paper());
list.add(Move.stone());
list.add(Move.paper());
list.add(Move.scissors());
list.add(Move.paper());
list.add(Move.scissors());
list.add(Move.stone());
list.add(Move.stone());
System.out.println("Original:");
for (Move move : list) {
System.out.print(move + ", ");
}
System.out.println();
Collections.sort(list);
System.out.println("Sorted:");
for (Move move : list) {
System.out.print(move + ", ");
}
System.out.println();
}
static class Move implements Comparable<Move> {
public enum TYPE {
SCISSORS, PAPER, STONE
};
private TYPE type;
private int count;
public static int COUNT = 0;
private static Move paper() {
Move move = new Move();
move.type = TYPE.PAPER;
move.count = COUNT++;
return move;
}
private static Move scissors() {
Move move = new Move();
move.type = TYPE.SCISSORS;
move.count = COUNT++;
return move;
}
private static Move stone() {
Move move = new Move();
move.type = TYPE.STONE;
move.count = COUNT++;
return move;
}
public String toString() {
switch (type) {
case SCISSORS:
return "Scissors [" + count + "]";
case PAPER:
return "Paper [" + count + "]";
case STONE:
return "Stone [" + count + "]";
}
return "";
}
@Override
public int compareTo(Move o) {
switch (this.type) {
case SCISSORS:
switch (o.type) {
case SCISSORS:
return 0;
case PAPER:
return 1;
case STONE:
return -1;
}
case PAPER:
switch (o.type) {
case SCISSORS:
return -1;
case PAPER:
return 0;
case STONE:
return 1;
}
case STONE:
switch (o.type) {
case SCISSORS:
return 1;
case PAPER:
return -1;
case STONE:
return 0;
}
}
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment