我是C#
的新手,我正在尝试创建一个输入并计算出移动的程序:1次移动或2次移动以及这些移动的所有组合(排列)。
我的公式为n = ((n - 1) + (n - 2))
我遇到的问题是尝试输出结果 - 我尝试使用if then else逻辑循环它们但它是一团糟。我不确定如何构建一个数组来支持排列。
If I move n=1 the result is 1 (1)
If I move n=2 the results is 2 (11,2)
If I move n=3 the results is 3 (111,12,21)
If I move n=4 the results is 4 (1111,112,211,121,22)
任何帮助将不胜感激:)
谢谢!
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleAppFrog
{
public class Program
{
public void Main(string[] args)
{
// Number of moves by using only 1 or 2 moves
Console.WriteLine("Enter a number of moves?");
int myNumber = Convert.ToInt32(Console.ReadLine());
int combenations = 0;
Console.WriteLine("You Chose " + myNumber + " moves :)");
// Math = ((myNumber - 1) + (myNumber - 2)) = combenations
combenations = ((myNumber - 1) + (myNumber - 2));
Console.WriteLine("There are " + combenations + " combinations of moves");
// Need to output the permutations of combenations
var moves = "";
// Gives the 1 moves
for (int i = 1; i <= myNumber; i++)
{
moves += "1 ";
}
Console.WriteLine(moves);
var moves2 = "";
// Get the 2 moves and check for remainder
for (int i = 1; i <= (myNumber / 2); i++)
{
moves2 += "2 ";
}
var moves3 = "";
//need to add on 1 move if there is a remainder
if (myNumber % 2 != 0)
{
moves3 += "1 ";
}
Console.WriteLine(moves2 + moves3);
Console.WriteLine(moves3 + moves2);
// Stuck trying to figure out the rest of moves
//-------------------------------------------------------------------------
Console.WriteLine("Done...");
Console.Read();
}
}
}
答案 0 :(得分:1)
你可能会有一个递归函数更好的运气。
修改强> 在您的代码中看起来像这样
using System;
namespace ConsoleAppFrog
{
public class Program
{
public void Main(string[] args)
{
// Number of moves by using only 1 or 2 moves
Console.WriteLine("Enter a number of moves?");
int myNumber = int.Parse(Console.ReadLine());
GenerateMoves (myNumber);
Console.WriteLine("Done...");
Console.Read();
}
static void GenerateMoves(int n) {
GenerateMoves (n, "");
}
static void GenerateMoves(int n, string permutation) {
if (n==0) { System.Console.WriteLine (permutation); }
else {
if (n>=1) { GenerateMoves (n-1, permutation + "1"); }
if (n>=2) { GenerateMoves (n-2, permutation + "2"); }
}
}
}
}