Skip to content

Instantly share code, notes, and snippets.

@DavidCulpepper
Last active August 29, 2015 13:56
Show Gist options
  • Save DavidCulpepper/8826724 to your computer and use it in GitHub Desktop.
Save DavidCulpepper/8826724 to your computer and use it in GitHub Desktop.
public class Keypad {
private String passcode;
private Dispatch police;
public Keypad(String passcode, Dispatch police) {
this.passcode = passcode;
this.police = police;
}
public boolean enterCode(String code) {
if (code.equals(passcode)) {
return true;
} else {
int softMistakes = 0;
for (int i = 0; i < code.length(); i++) {
if (code.charAt(i) != passcode.charAt(i)) {
if (hardFault(Integer.parseInt("" + code.charAt(i), Integer.parseInt("" + passcode.charAt(i))) {
police.alarm();
return false;
} else {
softMistakes++;
}
}
}
if (softMistakes > 1) {
police.alarm()
}
return false;
}
}
private boolean hardFault(int actual, int expected) {
int actualRow = (actual - 1) / 3;
int actualColumn = (actual - 1) % 3;
int expectedRow = (expected - 1) / 3;
int expectedColumn = (expected - 1) % 3;
if (actualRow == expectedRow) {
return actualColumn - 1 != expectedColumn && actualColumn + 1 != expectedColumn;
}
if (actualColumn == expectedColumn) {
return actualRow - 1 != expectedRow && actualRow + 1 != expectedRow;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment