Last active
October 29, 2016 19:28
-
-
Save rorosaurus/e0e9354878a49cb51705 to your computer and use it in GitHub Desktop.
SHOTS
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 static void main(String args[]){ | |
final int startingShot = 1; | |
ArrayList<Integer> startingList = new ArrayList<Integer>(); | |
// fill list with shots | |
for(int i=0;i<1024;i++){ | |
startingList.add(i, i+1); | |
} | |
// find solution | |
for (int solution=0;solution<=1024;solution++){ | |
// init | |
int currentShotIndex = startingShot-1; | |
ArrayList<Integer> shotsList = (ArrayList<Integer>)startingList.clone(); | |
// take shots until just 7 is left | |
while(!allShotsBut7(shotsList)){ | |
// find next shot, Circle back around | |
for(int i=0; i<solution; i++){ | |
currentShotIndex = (currentShotIndex+1) % shotsList.size(); | |
} | |
//shoot | |
if (shotsList.get(currentShotIndex) == 7)break; | |
shotsList.remove(currentShotIndex); | |
// recover if we're now outside of the circle as a result of last shot | |
if (currentShotIndex > shotsList.size()-1){ | |
currentShotIndex = 0; | |
} | |
} | |
if (allShotsBut7(shotsList)){ | |
System.out.println("Only shot 7 is left! Solution found: " + solution); | |
} | |
} | |
} | |
public static boolean allShotsBut7(ArrayList<Integer> list){ | |
return (list.get(0) == 7 && list.size() == 1); | |
} |
There is an excellent writeup of this problem in Donald Knuth’s Concrete Mathematics (Chapter 1, Section 3), which gives a closed form solution and the intuition behind it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Josephus takes out a tiny flag on a tiny stick and places it in the glass in
front of you and says:
Let's call this shot number 7, you must start at shot number 1. You pick a
number between 0 and 1024 and that is how many glasses you skip before taking
the next shot. Once you take a shot that glass is removed from the bar. You
continue around the bar skipping and drinking, over and over, until you have
consumed all the drinks except for number 7, then you can take the flag.
What number do you choose?