As a learning exercise I 'm working on a URL shortener that takes a URL and shortens it, similar to https://tinyurl.com/
This code:
import java.util.HashMap;
import java.util.Random;
/*
* URL Shortener
*
* https://gist.github.com/rakeshsingh/64918583972dd5a08012
*
*/
public class URLShortener {
// storage for generated keys
private HashMap<String, String> keyMap; // key-url map
private char myChars[]; // This array is used for character to number
// mapping
private Random myRand; // Random object used to generate random integers
private int keyLength;
// Constructor which enables you to define tiny URL key length and base URL
// name
public URLShortener(int keyLength) {
this.setup();
this.keyLength = keyLength;
}
private void setup(){
keyMap = new HashMap<String, String>();
myRand = new Random();
myChars = new char[62];
for (int i = 0; i < 62; i++) {
int j = 0;
if (i < 10) {
j = i + 48;
} else if (i > 9 && i <= 35) {
j = i + 55;
} else {
j = i + 61;
}
myChars[i] = (char) j;
}
}
// shortenURL
// the public method which can be called to shorten a given URL
public String shortenURL(String longURL) {
String key = "";
for (int i = 0; i <= keyLength; i++) {
key += myChars[myRand.nextInt(62)];
}
return key;
}
// generateKey
//Why is upper bound 62?
private String generateKey() {
String key = "";
boolean flag = true;
for (int i = 0; i <= keyLength; i++) {
key += myChars[myRand.nextInt(62)];
}
return key;
}
// test the code
public static void main(String args[]) {
URLShortener u = new URLShortener(5);
String urls[] = { "www.google.com/", "www.google.com",
"http://www.yahoo.com", "www.yahoo.com/",
"www.icicibank.com"
, "www.icicibank.com"};
for (int i = 0; i < urls.length; i++) {
System.out.println("URL:" + urls[i] + "\tTiny: "
+ u.shortenURL(urls[i]));
}
}
}
prints:
URL:www.google.com/ Tiny: wx4oPv
URL:www.google.com Tiny: S2JT01
URL:http://www.yahoo.com Tiny: jFOksR
URL:www.yahoo.com/ Tiny: EYcQ8o
URL:www.icicibank.com Tiny: V5JOn3
URL:www.icicibank.com Tiny: u4xQzn
The above code is refactored from https://gist.github.com/rakeshsingh/64918583972dd5a08012
I'm trying to understand this code block in particular:
private void setup(){
keyMap = new HashMap<String, String>();
myRand = new Random();
myChars = new char[62];
for (int i = 0; i < 62; i++) {
int j = 0;
if (i < 10) {
j = i + 48;
} else if (i > 9 && i <= 35) {
j = i + 55;
} else {
j = i + 61;
}
myChars[i] = (char) j;
}
}
Why iterate over a char array of 62 elements and at location i < 10
add 48 to the current char position, at location (i > 9 && i <= 35)
and 55 to the current char position and for all other positions add 61 ?