gpt4 book ai didi

c# - 迭代非方(某种)矩阵

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:08 26 4
gpt4 key购买 nike

我有一个这样的字典(样本数据因此没有意义):

Dictionary<char, string[]> codes = new Dictionary<char, string[]>();

string[] 是字典键的可能替换数组。

正在用一些示例数据填充字典...

codes.Add("A", new string[] {"噅噅", "裧", "頖", "11"});
codes.Add("B", new string[] {"垥", "2", "鉠"});
codes.Add("C", new string[] {"33", "韎"});
codes.Add("D", new string[] {"櫋", "緟", "嘕", "鈖", "灡", "犅"});
...
codes.Add("T", new string[] {"濇", "汫", "岕", "5"});
...

现在让我们“编码”以下单词:

    char[] charArray = "act".ToCharArray();
foreach (char c in charArray) {
string[] replacements = codes[c].Where(x => !String.IsNullOrEmpty(x)).ToArray();//removing empty elements

...
}

我现在不知道下一步该做什么,我想要一个所有可能组合的列表,它应该返回一个像这样的列表(对于单词“act”):

噅噅韎5

裧33濇

裧33汫

裧33岕

裧335

裧韎濇

裧韎汫

裧韎岕

...

由于 stackoverflow 的垃圾邮件过滤器,无法显示所有组合...

最佳答案

帖子标题具有误导性。如果我理解正确,您想使用 codes 作为输入字符替换来生成所有组合。

我已经回答了一个类似的问题 ( String combinations with multi-character replacement ),但是由于 string[] 部分,我无法直接重用 Looking at each combination in jagged array 中的方便代码,因此我将针对您的情况使用相同的算法:

public static class Algorithms
{
public static IEnumerable<string> GetCombinations(this string input, Dictionary<char, string[]> replacements)
{
var map = new string[input.Length][];
for (int i = 0; i < map.Length; i++)
{
var c = input[i];
string[] r;
map[i] = replacements.TryGetValue(c, out r)
&& (r = r.Where(s => !string.IsNullOrEmpty(s)).ToArray()).Length > 0 ?
r : new string[] { c.ToString() };
}
int maxLength = map.Sum(output => output.Max(s => s.Length));
var buffer = new char[maxLength];
int length = 0;
var indices = new int[input.Length];
for (int pos = 0, index = 0; ;)
{
for (; pos < input.Length; pos++, index = 0)
{
indices[pos] = index;
foreach (var c in map[pos][index])
buffer[length++] = c;
}
yield return new string(buffer, 0, length);
do
{
if (pos == 0) yield break;
index = indices[--pos];
length -= map[pos][index].Length;
}
while (++index >= map[pos].Length);
}
}
}

测试:

var codes = new Dictionary<char, string[]>();
codes.Add('A', new string[] { "噅噅", "裧", "頖", "11" });
codes.Add('B', new string[] { "垥", "2", "鉠" });
codes.Add('C', new string[] { "33", "韎" });
codes.Add('D', new string[] { "櫋", "緟", "嘕", "鈖", "灡", "犅" });
//...
codes.Add('T', new string[] { "濇", "汫", "岕", "5" });
//...

var test = "ACT".GetCombinations(codes).ToList();

关于c# - 迭代非方(某种)矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com