Создание короткого URL, подобного TinyURL.com

Избавление от предописаний:

struct global
{
     void main()
     {
           a = 1;
           b();
     }
     int a;
     void b(){}
}
singleton;

операторы переключения Записи с?: операторы:

string result = 
    a==0 ? "zero" :
    a==1 ? "one" :
    a==2 ? "two" :
    0;

Выполнение всего на одной строке:

void a();
int b();
float c = (a(),b(),1.0f);

структуры Обнуления без memset:

FStruct s = {0};

угол Нормализации/обертывания - и временные стоимости:

int angle = (short)((+180+30)*65536/360) * 360/65536; //==-150

Присваивающиеся ссылки:

struct ref
{
   int& r;
   ref(int& r):r(r){}
};
int b;
ref a(b);
int c;
*(int**)&a = &c;
10
задан CloudyMarble 8 August 2011 в 04:10
поделиться

5 ответов

Please, check out this good explanation on subject: Random TinyURL Browser (Updated) .

Important part:

As we have established, there are 62,193,780 possible values for TinyURL's. TinyURL's are generated by a Base 36 hash (36 indicating the number of characters a-z and 0-9, the array of possible values out of which a TinyURL can be constructed), autoincremented by MySQL with an initial value count of zero.

BTW, another SO similar question, through a mathematical view : Creating your own Tinyurl style uid. And here some .NET source code: Base 36 type for .NET (C#)

7
ответ дан 4 December 2019 в 01:01
поделиться

They use base 36 encoding, and you can make your app more robust by using base 64.

Here's what I'd try in Python (I do see your language tags, forgive me):

#!/usr/bin/python

from base64 import b64encode
from hashlib import sha1

for i in range(5):
    salted_int = "<salt>%s</salt>" % i
    print b64encode(sha1(salted_int).hexdigest())[:6]

Outputs:

NTUwMz
ZTVmZD
OGEzNm
Njc2MT
YzVkNj

So you can autoincrement an integer and feed it to some kind of function like this, and end up with a good chance of a random group of strings. See also my answer to this question. Some base64 implementations have the potential to emit a slash / or a plus sign +, and therefore you should keep an eye out for these in your implementation as they're dangerous in URLs.

Hashes are really flexible and prevent your users from guessing the next URL (if this is important to you).

2
ответ дан 4 December 2019 в 01:01
поделиться

I recently saw something like this on codeplex for sharepoint and they seemed to use hexadecimal numbers for the url shortener. It might be worth taking a look at how they do it here http://spurlshortener.codeplex.com/

1
ответ дан 4 December 2019 в 01:01
поделиться

Мои первоначальные мысли заключаются в том, чтобы сохранить число в базе данных и вывести его в ШЕСТНАДЦАТЕРИЧНОМ формате, чтобы оно было короче целого .

В чем смысл сохранить что-нибудь короче целого?
Итак, вы хотите, чтобы URL-адрес выглядел так: http: //here.there/ 12D687 вместо http: //here.there/ 1234567 ?

Если вы спросите меня, какой из них мне проще, я отвечу второму.
Но, честно говоря, я не вижу смысла в моем примере, поскольку оба они в значительной степени одинаковы.

Есть ли простой способ сгенерировать нечто подобное тому, что делает TinyURL?

Да. Попросите пользователя предоставить его.
Если это невозможно, просто используйте простой целочисленный идентификатор. Что может быть проще ...

-1
ответ дан 4 December 2019 в 01:01
поделиться

Еще один проект asp.net с открытым исходным кодом, который вы должны исследовать: мини-URL

2
ответ дан 4 December 2019 в 01:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: