I wrote a code to convert an Integer
between 1 and 238328 to a unique String
, formed from base62 characters (A-Za-z0-9) and of length 3. The String
generated can be reconverted to get back the initial Integer
.
For example, if the number was 238328 I can convert it to "zzz". I want to be able to use that String
"zzz" and get back the number 238328. I have written 2 methods to perform these operations and based on my testing it is working fine.
I am looking for some inputs on making it more readable and possibly more efficient. The conversion consists of 3 nested loops which really does not look right, though I can't get my head around a better way to do this.
class Permutation {
private final String[] DICTIONARY = new String[]{
"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
private Map<String, Integer> codes = new HashMap<>();
private Map<Integer, String> numbers = new HashMap<>();
String generateCode(int num){
int maxNumber = 238328;
if(num > maxNumber || num < 1) return null;
if(numbers.containsKey(num)){
return numbers.get(num);
}
int counter = 0;
for (int i = 0; i < DICTIONARY.length; i++) {
for (int j = 0; j < DICTIONARY.length; j++) {
for (int k = 0; k < DICTIONARY.length; k++) {
String code = DICTIONARY[i] + DICTIONARY[j] + DICTIONARY[k];
counter++;
numbers.put(counter, code);
codes.put(code, counter);
if(counter == num) return code;
}
}
}
return null;
}
int decode(String code){
if(codes.containsKey(code)){
return codes.get(code);
}
return 0;
}
}