我需要找到多米诺骨牌瓷砖的线性链的所有可能性。
示例:
Tiles : [3/4] [5/6] [1/4] [1/6]
Possible chain : [3/4]-[4/1]-[1/6]-[6/5]
Here我找到了一个用Java语言编写的示例。我是新手,因此我需要帮助将Java代码转换为c#。我知道语言非常相似。
private static void listChains(List<Domino> chain, List<Domino> list)
{
for (int i = 0; i < list.Count; ++i)
{
Domino dom = list[i];
if (canAppend(dom, chain))
{
chain.Add(dom);
Console.WriteLine(chain);
Domino saved = list.RemoveAt(i);
listChains(chain, list);
list.Add(new Domino(i, saved));
chain.Remove(chain.Count() - 1);
}
dom = dom.flipped();
if (canAppend(dom, chain))
{
chain.Add(dom);
Console.WriteLine(chain);
Domino saved = list.RemoveAt(i);
listChains(chain, list);
list.Add(new Domino(i, saved));
chain.RemoveAt(chain.Count() - 1);
}
}
}
严重性代码描述项目文件行抑制状态
错误CS1503参数2:无法从'ConsoleApp2.Domino'转换为'int'23 Active
错误CS0029无法将类型'void'隐式转换为'ConsoleApp2.Domino'21 Active
错误CS1503参数1:无法从'int'转换为'ConsoleApp2.Domino'24 Active
错误CS0029无法将类型'void'隐式转换为'ConsoleApp2.Domino'31 Active
错误CS1503参数2:无法从'ConsoleApp2.Domino'转换为'int'33 Active
错误CS1061'int'不包含'b'的定义,并且找不到可以接受的扩展方法'b'接受类型为'int'的第一个参数(您是否缺少using指令或程序集引用?)42 Active < br />
Domino saved = list.RemoveAt(i); list.Add(new Domino(i, saved));
chain.Remove(chain.Count() - 1); Domino saved = list.RemoveAt(i);
list.Add(new Domino(i, saved));
我不确定此方法的作用:(以及如何转换为c#)
private static boolean canAppend(Domino dom, List<Domino> to) {
return to.isEmpty() || to.get(to.size()-1).b == dom.a;
}
答案 0 :(得分:0)
以下是您发布的代码转换的截图:
public class Domino
{
public int A { get; set; }
public int B { get; set; }
public Domino(int a, int b)
{
A = a;
B = b;
}
public Domino Flipped()
{
return new Domino(B, A);
}
public override string ToString()
{
return $"[{A}/{B}]";
}
}
public class Program
{
private static void ListChains(List<Domino> chain, List<Domino> list)
{
for (int i = 0; i < list.Count; ++i)
{
Domino dom = list[i];
if (CanAppend(dom, chain))
{
chain.Add(dom);
Console.WriteLine(string.Join("-", chain));
Domino saved = list[i];
list.RemoveAt(i);
ListChains(chain, list);
list.Insert(i, saved);
chain.RemoveAt(chain.Count - 1);
}
dom = dom.Flipped();
if (CanAppend(dom, chain))
{
chain.Add(dom);
Console.WriteLine(string.Join("-", chain));
Domino saved = list[i];
list.RemoveAt(i);
ListChains(chain, list);
list.Insert(i, saved);
chain.RemoveAt(chain.Count - 1);
}
}
}
private static bool CanAppend(Domino domino, List<Domino> chain)
{
return chain == null || chain.Count == 0 || chain.Last().B == domino?.A;
}
private static void Main()
{
var dominos = new List<Domino>
{
new Domino(3, 4),
new Domino(5, 6),
new Domino(1, 4),
new Domino(1, 6)
};
ListChains(new List<Domino>(), dominos);
Console.ReadKey();
}
}
输出