Short URL Service (tinyurl) generation algorithm

Source: Internet
Author: User

A coupon sharing feature was recently made, and one of the features was to generate a coupon sharing short link. The resulting short link requires that each link be unique, and that the length is as short as possible. On the internet to look up the relevant ideas, found a good algorithm. The idea of this algorithm is to use [a-za-z0-9] to establish a 62-length matrix, and then the matrix is scrambled, regenerated into a globally unique number, and then the number is represented in the matrix of the element representation into 62, the resulting link length of the largest only 11 bits. So the key to the generation of short links becomes how to generate a globally unique number and implement a binary conversion.

1. Generate globally unique numbers

This is essentially a distributed ID problem. If it is simple, you can borrow Redis's incr operation so that each time you get the ID is monotonically incremented and unique. Another way is to borrow MySQL, which is not the AUTO_INCR feature that borrows the MySQL primary key. Instead, each application allocates a range for the request, such as S1 [100-200], which is assigned [201-301] when requested by S2, essentially using an optimistic lock to perform a CAS operation.

If you do not want to use external to generate ID, you can use the UUID algorithm. The UUID length consists of 12 bytes consisting of the following parts.

    • A 4-byte representation of the Unix timestamp,
    • The ID of the machine represented by a 3-byte
    • 2 bytes representing the process ID
    • 3 bytes of counter

UUID is a generic term for a class of algorithms, with different implementations. The advantage is that each machine can independently generate ID, theoretically guaranteed not to repeat, so the natural is distributed, the disadvantage is that the generated ID is too long, not only occupy memory, but also low efficiency index query.

There is also a Twitter snowflake algorithm, which essentially looks similar to the UUID .

In General, the Redis,mysql solution is simpler and more straightforward to meet most scenarios, and the UUID and Twitter snowflake algorithms are more appropriate and relatively complex to implement if high performance and availability are to be ensured.  

2. Binary conversion

This is a relatively simple operation. Directly on the code ~

/** * Short chain delivered into */public class TinyURL {public static final char[] array = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5                    ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' Q ', ' W ', ' e ', ' r ', ' t ', ' y ', ' u ', ' i ', ' o ', ' P ', ' a ', ' s ', ' d ',  ' F ', ' g ', ' H ', ' J ', ' K ', ' l ', ' Z ', ' x ', ' C ', ' V ', ' b ', ' n ', ' m ', ' Q ', ' W ', ' E ', ' R ', ' T ', ' Y ', ' U ',    ' I ', ' O ', ' P ', ' A ', ' S ', ' D ', ' F ', ' G ', ' H ', ' J ', ' K ', ' L ', ' Z ', ' X ', ' C ', ' V ', ' B ', ' N ', ' M ';    public static Map<character, integer> Charvaluemap = new Hashmap<character, integer> ();    Initialize map static {for (int i = 0; i < array.length; i++) Charvaluemap.put (Array[i], i); public static void Main (string[] args) {for (int i = 0; i <; i++) {Long number = Long.max_            Value-i;            String decimalstr = numberconverttodecimal (number, 62);            SYSTEM.OUT.PRINTLN (number + "convert to" + decimalstr); Long Tonumber = DecimalconverttonuMber (Decimalstr, 62);        System.out.println (Decimalstr + "convert to" + Tonumber); }}/** * Converts the number into a corresponding binary, currently supports (2-62) binary * * @param numbers * @param decimal * @return */Publi        C Static String Numberconverttodecimal (long number, int decimal) {StringBuilder builder = new StringBuilder ();            while (number! = 0) {builder.append (array[(int) (number-(number/decimal) * decimal)]);        Number/= decimal;    } return Builder.reverse (). toString (); /** * Convert the binary string to the corresponding number * @param decimalstr * @param decimal * @return */public static long Deci        Malconverttonumber (String decimalstr, int decimal) {long sum = 0;        Long multiple = 1;        char[] chars = Decimalstr.tochararray ();            for (int i = chars.length-1; I >= 0; i--) {char c = chars[i];            Sum + = Charvaluemap.get (c) * multiple;        multiple *= decimal;    } return sum; }} 

There's a small optimization that uses Charvaluemap to record the corresponding value of each character, which is a strategy optimization using space-time change, and the O (n) time is reduced to O (1).

In addition, we usually want to record short URLs and long URLs corresponding to the relationship, relative to the direct storage of short URLs, store the corresponding numeric ID will be more space-saving.

Short URL Service (tinyurl) generation algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.