首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >生成2-4个字符α-数值

生成2-4个字符α-数值
EN

Stack Overflow用户
提问于 2013-11-25 19:16:58
回答 2查看 490关注 0票数 0

我需要一个在c#中返回一个c#的函数。

该函数需要返回所有可能性,以便:

2-4个字符字母数字(a-z A-Z0-9)

你有什么目的来做一个快速生成功能吗?(需要快速生成)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-25 19:50:00

首先,如果你想把它作为一个列表,你肯定不会把它放进任何现有的内存中。大概是(58^10+58^9+58^8.字节数)。

但是,您可以尝试这样的方法:

代码语言:javascript
运行
复制
// this generates all strings for characters 0-3 with lengths 2-3
List<string> result = GenerateStrings("0123", 2, 3);

private List<string> GenerateStrings(string allowedChars, int fromLength, int toLength)
{
    List<string> strings = new List<string>();

    int charsNum = allowedChars.Length;

    for (int currentLength = fromLength; currentLength <= toLength; currentLength++)
    {
        // initialize array of indexes to generate individual characters
        int[] indexes = new int[currentLength];
        do
        {
            StringBuilder sb = new StringBuilder(currentLength);
            // generate characters based on current index values
            for (int charPosition = 0; charPosition < currentLength; charPosition++)
            {
                sb.Append(allowedChars[indexes[charPosition]]);
            }
            strings.Add(sb.ToString());
            // until we can increment indexes array (still some character combinations available)
        } while (IncrementIndex(indexes, charsNum - 1, currentLength - 1));
    }

    return strings;
}

/// <summary>
/// Have array of integer indexes such as [0,0,0] with valid values 0-9. 
/// This function increments indexes from right by one with correct overflow handling, 
/// such that value [0,0,3] is incremented to [0,0,4], value [0,2,9] to [0,3,0] etc.
/// </summary>
/// <returns>True if increment was successful, false if maximal value was reached.</returns>
private bool IncrementIndex(int[] indexes, int maxItemValue, int incrementFromPosition)
{
    indexes[incrementFromPosition]++;
    // check if current position overflow allowed range
    if (indexes[incrementFromPosition] > maxItemValue)
    {
        if (incrementFromPosition == 0)
        {
            // we reached left-most position and can't increment more
            return false;
        }

        indexes[incrementFromPosition] = 0;
        // increment next position to the left
        return IncrementIndex(indexes, maxItemValue, incrementFromPosition-1);
    }

    return true;
}
票数 1
EN

Stack Overflow用户

发布于 2013-11-25 19:43:14

尝尝这个

List lst =新List() { "a“、"b”、"c“、"d”、"e“、"f”、"g“、"h”};

代码语言:javascript
运行
复制
        List<string> newlst = (from p in lst
                               from q in lst
                               select p + q).ToList();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20201348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档