Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java Programming Help?
A king once decided to grant amnesty to some of his prisoners due to lack of jail space rather than build a new prison. He instructed his jailer to carryout the following procedure to determine which prisoners were to be set free. The jailer was to first unlock each of the 1000 cells. Then starting with the 2nd cell (number 2), he turned the key in every 2nd cell. Then starting with the 3rd cell he turned the key in every 3rd cell; then starting the 4th, he turned the key in every 4th cell, etc. Each turn of the key either locked or unlocked the cell door. When he was completely done those with the unlocked doors could leave. Who were the lucky ones?
1 Answer
- deonejuanLv 71 decade agoFavorite Answer
import java.util.Arrays;
public class OneThousandJailCells {
static final int HOOSEGOWS = 1000;
static boolean[] locks = new boolean[HOOSEGOWS];
public static void main(String[] args) {
Arrays.fill(locks, true); // jailer keeps them locked
int[] skipees = {2, 3, 4};
Arrays.fill(locks, false); // they are all unlocked on holiday
for (int i = 0; i < skipees.length; i++) {
System.out.println("Jailer pass no " + (i + 1) + ", skip every " + skipees[i]);
jailerWork(skipees[i]);
}
System.out.println("\n\nthe lucky ones are:::::::::::::");
int luckies = 0;
for (int i = 0; i < locks.length; i++) {
if( !locks[i]) {
System.out.printf("Cell no %3d unlocked%n", i+1);
luckies ++;
}
}
System.out.printf("Unlocked cells %d%n",luckies);
}
static private void jailerWork(int start) {
for (int i = start; i < locks.length; i++) {
locks[i - 1] = !locks[i - 1];
i += start;
}
int t = inventory(locks);
System.out.println("+===============" + t + " unlocked cells\n");
}
static private int inventory(boolean[] l) {
int totals = l.length;
for (int i = 0; i < l.length; i++) {
if (l[i]) {
System.out.printf("Hoosegow No: %3d locked%n", i + 1);
totals--;
}
}
return totals;
}
}