Skip to content

Instantly share code, notes, and snippets.

@minor
Created March 26, 2020 18:07
Show Gist options
  • Save minor/f416d3f42d8868e21df1532ce2e9b768 to your computer and use it in GitHub Desktop.
Save minor/f416d3f42d8868e21df1532ce2e9b768 to your computer and use it in GitHub Desktop.
LockerPuzzle.java; Professor Estrada HW
package com.saurishsrivastava;
/* name: Saurish Srivastava; locker puzzle, will determine whether or not the locker is opened after a series of students opening it: 10 PM on 24 March 2020 */
public class LockerPuzzle {
/**
* Main method
*/
public static void main(String[] args) {
/* create the Locker array */
boolean[] lockers = new boolean[101]; // create a locker array of 101 booleans (we will get rid of the 0th boolean)
/* First we need to close all the lockers */
lockersClosed(lockers);
/* Next we need to run all of the student trials */
studentsTrial(lockers);
/* Lastly we need to print out the open lockers */
printFunction(lockers);
}
public static boolean isOpen(boolean i) {
return i; // if the boolean is true (open) it will return true, if not, it will return false (closed)
}
/* Close all the lockers in the array */
public static void lockersClosed(boolean[] lockers) {
for(int x = 0; x < lockers.length; x++) {
lockers[x] = false; // could also be achieved with the ArrayFill method
}
}
/* Run the students closing the lockers in their patterns */
public static void studentsTrial(boolean[] lockers) {
for (int y = 1; y <= (lockers.length); y++) { // the first for loop counts how many people have gone
for(int z = 0; z < lockers.length; z+=y) { // z+y because fourth person will go every FOURTH locker etc
if (isOpen(lockers[z])) {
lockers[z] = false; // set the locker to false if it is currently true
} else {
lockers[z] = true; // set the locker to true if it is currently false
}
}
}
}
public static void printFunction(boolean[] lockers) {
for (int z = 1; z < lockers.length; z++) { // only take from z=1 because we don't include locker 0.
if (isOpen(lockers[z])) {
System.out.print("L" + (z) + " "); // use print not println so it can work numerous times and be in one line; z+1 bc we start at 0 but there is no locker number 0
} // no need for else statement bc we don't need to do anything to the lockers that are closed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment