本文介绍了如何创建在C#中人物的独特的随机序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实现我的应用程序中的网址缩短功能,以提供可在微博中使用我的用户可选择较短的URL。关键是要独立于缩短的服务,提供同样的服务,并把它作为我的web应用程序的功能。

I'm implementing a URL shortening feature in my application in order to provide my users shorter alternative URLs that can be used in Twitter. The point is to be independent from the shortening services that offer this same service and include it as a feature of my web app.

什么是创建一个唯一的随机的最佳方式约6个字符的字符序列?我打算使用作为我的数据库中的项目,将有替代网址索引

What's the best way to create an unique random sequence of characters of about 6 chars? I plan to use that as an index for the items in my database that will have the alternative URLs.

编辑:

这个功能将在一个工作委员会网站,在那里每一个新的招聘广告将获得与标题自定义URL加上较短的在微博中使用使用。这就是说,独特的6字符组合的总数将是绰绰有余了很长时间。

This feature will be used in a job board website, where every new job ad will get a custom URL with the title plus the shorter one to be used in Twitter. That said, the total number of unique 6 char combinations will be more than enough for a long time.

推荐答案

你真的需要随机,或将独一无二就足够了?

Do you really need 'random', or would 'unique' be sufficient?

独特的是非常简单 - 只需插入网址到数据库中,并转换顺序编号为记录是由您选择的字符集为代表的碱基-N数字。

Unique is extremely simple - just insert the URL into a database, and convert the sequential id for that record to a base-n number which is represented by your chosen characterset.

例如,如果您希望只使用[AZ]在你的顺序,你的记录的ID转换为基26号,其中A = 1,b = 2,... Z = 26。所述algothithm是一个递归div26 / mod26,其中的商为所需要的字符,其余被用于计算下一个字符。

For example, if you want to only use [A-Z] in your sequence, you convert the id of the record to a base 26 number, where A=1, B=2,... Z=26. The algothithm is a recursive div26/mod26, where the quotient is the required character and the remainder is used to calculate the next character.

然后检索网址时,执行反函数,这是基26号转换回小数。 !执行SELECT URL WHERE ID =小数,就大功告成了。

Then when retrieving URL, you perform the inverse function, which is to convert the base-26 number back to decimal. Perform SELECT URL WHERE ID = decimal, and you're done!

编辑:

private string alphabet = "abcdefghijklmnopqrstuvwxyz"; 
   // or whatever you want.  Include more characters 
   // for more combinations and shorter URLs

public string Encode(int databaseId)
{
    string encodedValue = String.Empty;

    while (databaseId > encodingBase)
    {
        int remainder;
        encodedValue += alphabet[Math.DivRem(databaseId, alphabet.Length, 
            out remainder)-1].ToString();
        databaseId = remainder;
    }
    return encodedValue;
}

public int Decode(string code)
{
    int returnValue;

    for (int thisPosition = 0; thisPosition < code.Length; thisPosition++)
    {
        char thisCharacter = code[thisPosition];

        returnValue += alphabet.IndexOf(thisCharacter) * 
            Math.Pow(alphabet.Length, code.Length - thisPosition - 1);
    }
    return returnValue;
}

这篇关于如何创建在C#中人物的独特的随机序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:01