Last active
August 29, 2015 13:56
-
-
Save DavidCulpepper/8826724 to your computer and use it in GitHub Desktop.
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 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