Skip to content

Instantly share code, notes, and snippets.

@korzha
Created September 27, 2019 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korzha/8ec7d26c1706cc6f9edec05e3dcd37fb to your computer and use it in GitHub Desktop.
Save korzha/8ec7d26c1706cc6f9edec05e3dcd37fb to your computer and use it in GitHub Desktop.
PINs generator problem
import java.util.Collection;
import java.util.Objects;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
assertEquals("0,5,7,8,9", getPossiblePins("8"));
assertEquals("11,12,14,21,22,24,41,42,44", getPossiblePins("11"));
assertEquals("13,15,16,19,43,45,46,49,53,55,56,59,73,75,76,79", getPossiblePins("46"));
}
private static void assertEquals(String expected, String actual) {
if (!Objects.equals(expected, actual)) {
throw new AssertionError("expected: " + expected + " but was: " + actual);
}
}
public static String getPossiblePins(String pin) {
Collection<String> pins = new TreeSet<>();
generatePins("", pin, pins);
return String.join(",", pins);
}
private static void generatePins(String prefix, String suffix,
Collection<String> pins) {
pins.add(prefix + suffix);
if (suffix.isEmpty()) {
return;
}
String closeDigits = getCloseDigits(suffix.charAt(0));
suffix = suffix.substring(1);
for (int i = 0; i < closeDigits.length(); i++) {
char nextDigit = closeDigits.charAt(i);
generatePins(prefix + nextDigit, suffix, pins);
}
}
private static String getCloseDigits(char c) {
switch (c) {
case '0':
return "08";
case '1':
return "124";
case '2':
return "1235";
case '3':
return "236";
case '4':
return "1457";
case '5':
return "24568";
case '6':
return "3569";
case '7':
return "478";
case '8':
return "57890";
case '9':
return "689";
default:
throw new IllegalArgumentException("illegal number");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment