我尝试创建一个像
a,b,c,...z,aa,ab,ac,ad,ae,af,...,az,ba,bb,bc,...,bz,..zz,aaa,aab,aac..
给定的字母系列number(N)
但是当我尝试使用创建它时for loops
,我for loop
在元素中每秒创建一个字符,这意味着打印 a..z - loop1,a
对于每一秒的字母a
,我写一个新的 for 循环
是否可以使用 for 循环创建这种类型系列...
提前致谢...
这是如何做到的:
public static string GetExcelColumnName(int index)
{
int d = index;
string name = "";
int mod;
while (d > 0)
{
mod = (d - 1) % 26;
name = Convert.ToChar('a' + mod).ToString() + name;
d = (int)((d - mod) / 26);
}
return name;
}
public static IEnumerable<string> GetExcelColumns(int n) {
for (int i = 1; i <= n; i++)
{
yield return GetExcelColumnName(i);
}
}
static void Main(string[] args)
{
int i = 1;
foreach (var item in GetExcelColumns(900))
{
Console.Write(i++ + ": " + item + " ");
}
Console.WriteLine();
}
解释GetExcelColumnName
:
//Suppose index = 1, `GetExcelColumnName` should return `"a"`.
d = 1
d > 0
mod = (d - 1) % 26; //mod now is 0
Convert.ToChar('a' + mod); // => That's 'a'
//name now is "a"
d = (d - mod) / 26 = (1 - 0) / 26 = 0 // d is now 0
//End of While
method returns "a"
//Suppose index = 28, `GetExcelColumnName` should return `"ab"`.
d = 28
d > 0
mod = (d - 1) % 26; //mod now is 1 (27 modulo 26)
Convert.ToChar('a' + mod); // => That's 'b'
//name now is "b"
d = (d - mod) / 26 = (28 - 1) / 26 = 1 // d is now 1
d > 0
mod = (d - 1) % 26; //mod now is 0 (0 modulo 26)
Convert.ToChar('a' + mod); // => That's 'a'
//name now is "ab"
d = (d - mod) / 26 = (1 - 0) / 26 = 0 // d is now 0
//End of While
method returns "ab"
这对于列表和理解非常简单
例如在python中
alpha = ['a','b','c','d','e','f','g','h','i']
def merge(x,y):
new = [ a+b for a in x for b in y]
return new
print(merge(alpha,alpha))
print(merge(alpha,merge(alpha,alpha)))
会给你你想要的。在 C# 中,您可以找到等价物(或在 F# 中)
我认为看待这个问题的正确方法是,以 27 为基数,并用 0 跳过所有数字。您的数字是_abcdefghijklmnopqrstuvwxyz
(_ 的值为 0,z 的值为 26),并且您像这样创建以 27 为基数的数字:
nums_generated = 0
next_num = 1
while nums_generated < N:
number_string = generate_base_27(next_num)
if not '_' in number_string:
print number_string
num_generated = num_generated + 1
next_num = next_num + 1
这应该够了吧。要使用给定的字符集创建以 27 为基数的数字,请在此处查看示例,并根据需要以 27 为基数进行适当的更正。