A short unique string identifier for shorten URL

How to shorten URLs? As far as you know, there is a lot of Short URL Redirection Services, such as "bit.ly", which used to convert a long url to some short url.

Its Mechanism seems simple. The sequential key for long URL is enough.
For example, the "Wa0e" is the key of "http://bit.ly/Wa0e"
for "http://www.beachbody.com/product/fitness_programs/p90x.do?code=P90XDOTCOM".
The mod_rewrite module could be used to remove file extension and parameters (e.g., short.php?key=Wa0e)

Key looks like a random string, but I guess it's just a sequential key. Because, that way is simple, and same with total number of random combination in conclusion.

How to generate sequential key? Below is my example code.

INDEX.length is 62. So, (62^4 -1) URLs could stored in the combination of four ciphers.

private static String[] INDEX = 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 static String getNextURL(String in) {
    if (in == null) {
      return INDEX[0];

    char[] result = new char[in.length()];
    boolean rounded = false;

    for (int i = in.length() - 1; i > -1; i--) {
      String subStr = Character.toString(in.charAt(i));
      try {
        if (!rounded) {
          result[i] = getNext(subStr).charAt(0);
          rounded = true;
        } else {
          result[i] = in.charAt(i);
      } catch (ArrayIndexOutOfBoundsException e) {
        result[i] = INDEX[0].charAt(0);

    return new String(result);

  private static String getNext(String subStr) {
    if (subStr.equals("Z")) {
      throw new ArrayIndexOutOfBoundsException();

    int x = 0;
    for (int i = 0; i < INDEX.length; i++) {
      if (INDEX[i].equals(subStr))


    return INDEX[x + 1];

No comments:

Post a Comment

무한의 세계

무한 집합의 크기 Cardinality , 즉 원소의 개수를 수학에서는 '농도'라고 말한다. 유한 집합의 크기는 그대로 원소의 개수 이지만, 무한 집합의 경우는 원소의 개수를 낱낱이 셈하는 것은 불가능하기 때문에 '농도'라...