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))
        break;

      x++;
    }

    return INDEX[x + 1];
  }

Comments

Popular posts from this blog

일본만화 추천 100선

구글링하는(googling) 방법

AWS re:Invent 2017 참관기