Skip to content

Instantly share code, notes, and snippets.

@cbojar
Last active August 29, 2015 14:03
Show Gist options
  • Save cbojar/de5d07357813cc8debec to your computer and use it in GitHub Desktop.
Save cbojar/de5d07357813cc8debec to your computer and use it in GitHub Desktop.
100 Gunmen
This is the code for my answer to the Code Review question at: http://codereview.stackexchange.com/questions/56951/100-gunmen-in-circle-kill-next-person
public class Gunman
{
private int number;
public Gunman(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
import java.util.*;
public class Main
{
public static final int NUMBER_OF_GUNMEN = 100;
public static void main(String[] args) {
List<Gunman> gunmen = new LinkedList<>();
for(int i = 1; i <= NUMBER_OF_GUNMEN; i++) {
gunmen.add(new Gunman(i));
}
while(gunmen.size() > 1) {
Iterator<Gunman> it = gunmen.iterator();
while(it.hasNext() && gunmen.size() > 1) {
Gunman killer = it.next();
if(!it.hasNext()) {
it = gunmen.iterator();
}
Gunman killed = it.next();
System.out.println(killer.getNumber() + " kills " + killed.getNumber());
it.remove();
}
}
System.out.println();
if(gunmen.size() == 0) {
System.out.println("No one lives and no one dies.");
} else {
System.out.println(gunmen.get(0).getNumber() + " lives another day...");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment