如何在 c# 中按顺序使用从“AAAAAA”到“ZZZZZZ”的值初始化字符串数组
本文关键字:AAAAAA ZZZZZZ 数组 字符串 初始化 顺序 | 更新日期: 2023-09-27 18:36:32
我想轻松地预填充一个单维字符串数组,我用以下值称为"字母":
AAAAAA
AAAAAB
AAAAAC
AAAAAD
..
..
ZZZZZX
ZZZZZY
ZZZZZZ
这是1.65亿种组合。
这个想法是我需要能够请求 6 个字符的任何特定组合,例如 BBCHHJ
并使用 Array.Index
返回它所在的数组元素。
我有第二点很好:
String searchFor;
Console.Write("Enter a string value to search for: ");
searchFor = Console.ReadLine();
int indexValue = Array.IndexOf(letters, searchFor);
Console.WriteLine("The value you are after is in element index: " + indexValue);
Console.ReadLine();
但是我不知道如何按顺序轻松地使用所有这些组合初始化字母数组!
Jakub答案的变体,应该更有效率:
int result = s
.Select(c => c - 'A') // map 'A'-'Z' to 0-25
.Aggregate(0, (total, next) => total * 26 + next); // calculate the base 26 value
这样做的好处是避免了Reverse
和单独的Sum
,并且 26 的幂不必在每次迭代中从头开始计算。
在数组中存储 3.08 亿个元素并搜索它们不是最好的解决方案,而是在运行时计算索引。我创建了一个代码示例:
string input = "ZZZZZZ";
//default values
string alphabets_s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] alphabets = alphabets_s.ToCharArray();
int result = 1; //starting with "one" because zero will make everything zero
//calculating index
for (int i = 0; i < input.Length; i++)
{
//get character index and add "1" to avoid multiplication with "0"
int index = Array.IndexOf(alphabets, input[i]) + 1;
//multiply it with the current result
result *= index;
}
//subtract 1 from final result, because we started it with 1
result--;
PS:我只是做了基本的测试,如果您发现其中有问题,请告诉我。
正如我在评论中所写,您要实现的基本上是从基数 26 的转换。
第一步是将字符串转换为数字列表。然后乘以 26 的幂并加在一起:
var s = "AAAABB";
var result = s
.Select(c => c - 'A') //map characters to numbers: A -> 0, B -> 1 etc
.Reverse() //reverse the sequence to have the least significant digit first
.Select((d, i) => d * Math.Pow(26, i))
.Sum();