Last active
August 29, 2015 14:03
-
-
Save cbojar/de5d07357813cc8debec to your computer and use it in GitHub Desktop.
100 Gunmen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Gunman | |
{ | |
private int number; | |
public Gunman(int number) { | |
this.number = number; | |
} | |
public int getNumber() { | |
return number; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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