gpt4 book ai didi

c# - 将数字字符串拆分为一位数和两位数的可能组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:16 24 4
gpt4 key购买 nike

我有一个数字字符串,我想将其拆分为一位数和两位数的可能组合。

例如:拆分字符串“59145”后我想有以下组合:

5 9 1 4 5
5 9 1 45
5 9 14 5
5 91 4 5
5 91 45
59 1 4 5
59 1 45
59 14 5

我当前的代码如下所示:

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
foreach (var combination in SplitNumbers("59145"))
{
foreach (var number in combination)
{
Console.Write(number + " ");
}
Console.WriteLine();
}

Console.Read();
}

static IEnumerable<List<string>> SplitNumbers(string input)
{
int numberCombinations = Fibonacci(input.Length + 1);

List<string> combination;
string temp;
int count;

for (int i = 0; i < numberCombinations; i++)
{
combination = new List<string>();
temp = input;
count = 0;

while (temp.Length > 0)
{
combination.Add(temp.Substring(0, combinations[input.Length][i][count]));
temp = temp.Remove(0, combinations[input.Length][i][count]);
count++;
}
yield return combination;
}
}

public static int Fibonacci(int n)
{
int a = 0;
int b = 1;

for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}

static int[][][] combinations = new int[][][]
{
//0 numbers
new int[][]
{
new int[]{0}
},
//1 number
new int[][]
{
new int[]{1}
},
//2 numbers
new int[][]
{
new int[]{1,1},
new int[]{2}
},
//3 numbers
new int[][]
{
new int[]{1,1,1},
new int[]{1,2},
new int[]{2,1}
},
//4 numbers
new int[][]
{
new int[]{1,1,1,1},
new int[]{1,1,2},
new int[]{1,2,1},
new int[]{2,1,1},
new int[]{2,2}
},
//5 numbers
new int[][]
{
new int[]{1,1,1,1,1},
new int[]{1,1,1,2},
new int[]{1,1,2,1},
new int[]{1,2,1,1},
new int[]{1,2,2},
new int[]{2,1,1,1},
new int[]{2,1,2},
new int[]{2,2,1}
}
};
}
}

我的问题是我必须对每个可能的组合进行硬编码。我确信有可能以编程方式解决此问题,但目前我不知道该怎么做。

最佳答案

使用递归,它会像这样完成:

static IEnumerable<List<string>> Split(string input)
{
return Split(input, new List<string>());
}

static IEnumerable<List<string>> Split(string input, List<string> current)
{
if (input.Length == 0)
{
yield return current;
}

if (input.Length >= 1)
{
var copy = current.ToList();
copy.Add(input.Substring(0, 1));
foreach (var r in Split(input.Substring(1), copy))
yield return r;
}

if (input.Length >= 2)
{
var copy = current.ToList();
copy.Add(input.Substring(0, 2));
foreach (var r in Split(input.Substring(2), copy))
yield return r;
}
}

这将打印项目列表:

foreach (var r in Split("59145"))
Console.WriteLine(string.Join(",", r));

这是一个working fiddle .

关于c# - 将数字字符串拆分为一位数和两位数的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25380719/

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