[英]It is possible to generate random numbers sequences from digits in c#?
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];
}
}
}
如您所願,我將此答案翻譯為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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.