stackoverflow社区,
我想制作c#应用程序,它可以生成数字序列(如果前一个数字的最后一位等于第二个数字的第一位)。例如,我有一个数据数组,其中包含:20、15、25、05、53、31,并且我需要创建所有可能的序列。
So, in my case it should be:
20 05 53;
02 25 53 31 15;
15 53 31;
25 53 31 15;
and etc...
给定数字的数字可以交换。在一个序列中,同一编号只能使用一次(例如20和02、15和51,它们只能在一个序列中使用一次) 好吧,我尝试了几种代码组合,但是都没有解决……
for (int i = 0; i < data.Length; i++)
{
string lastDigit = data[i].Substring(1, 1); // setting last digit of the first number
string generatedSequence = "";
for (int c = 0; c < data.Length; c++)
{
if (lastDigit == data[c].Substring(0, 1)) //if last digit of previous number equals to first digit of next number
{
lastDigit = data[c].Substring(1, 1); // second digit of the number
generatedSequence = generatedSequence + " " + data[c];
}
}
}
答案 0 :(得分:0)
如您所愿,我将this answer转换为C#
Domino类: `
public class Domino {
public Domino(int a, int b)
{
A = a;
B = b;
}
public int A { get; set; }
public int B { get; set; }
public Domino Flipped()
{
return new Domino(B, A);
}
public override string ToString()
{
return $"[{A}/{B}]";
}
}
算法:
public static void GetList(List<Domino> chain, List<Domino> list)
{
for (int i = 0; i < list.Count; i++)
{
Domino domino = list[i];
if (CanAppend(domino, chain))
{
chain.Add(domino);
PrintList(chain);
list.Remove(domino);
//You need to create these two lists via the new keyword because
//we do not want to keep up the reference to the "old" list.
//Otherwise changes in the recoursion would also change the top-level list.
GetList(new List<Domino>(chain), new List<Domino>(list));
list.Insert(i, domino);
chain.Remove(domino);
}
var flippedDomino = domino.Flipped();
if (CanAppend(flippedDomino, chain))
{
chain.Add(flippedDomino);
PrintList(chain);
list.Remove(domino);
GetList(new List<Domino>(chain), new List<Domino>(list));
list.Insert(i, domino);
chain.Remove(flippedDomino);
}
}
}
两种帮助方法:
public static bool CanAppend(Domino domino, List<Domino> items)
{
return items.Count == 0 || items.Last().B == domino.A;
}
private static void PrintList(List<Domino> items)
{
Console.WriteLine();
foreach (var item in items)
{
Console.Write(item.ToString());
}
}
这就是您的使用方式:
List<Domino> list = new List<Domino>();
// [3/4] [5/6] [1/4] [1/6]
list.Add(new Domino(3, 4));
list.Add(new Domino(5, 6));
list.Add(new Domino(5, 6));
list.Add(new Domino(1, 4));
list.Add(new Domino(1, 6));
List<Domino> chain = new List<Domino>();
GetList(chain, list);