我必须输入一个5字母的单词,然后它应该打印出不同的3个字母组合,但它不起作用,我不知道为什么。
E.g。如果我输入"你好",所有不同的组合,例如" leh"," lol"," hle"等应该返回。
static void Main(string[] args)
{
Console.Write("Enter a five-letter word: ");
String x = Console.ReadLine();
for (int i = 0; i < x.Length; i++)
{
char letter = x[i];
Random ran = new Random();
for (int z = 1; z < 4; z++)
{
char y = x[ran.Next(0, x.Length)];
Console.Write(y);
}
}
Console.WriteLine();
}
答案 0 :(得分:1)
我们可以将问题陈述分为两部分。
对于第一部分,我们将声明一个数组,该数组可能包含五个中的三个字符。通过提取的三个字符,我们将进行不同的组合。
注意:如果我错过了任何组合,您可以在arrIndexes中添加组合。
string word = "hello";
int [,] arrIndexes = new int[9,3] {{0,1,2}, {0,1,3}, {0,1,4}, {0,2,3}, {0,2,4}, {0,3,4}, {1,2,3}, {1,3,4}, {2,3,4}};
for(int i=0; i < 9; i++)
{
string sub = "";
for(int j=0; j<3; j++)
sub += word[arrIndexes[i,j]];
Console.Write("{0}{1}{2}",sub[0], sub[1], sub[2]);
Console.Write("\t{0}{1}{2}",sub[2], sub[1], sub[0]);
Console.Write("\t{0}{1}{2}",sub[1], sub[0],sub[2]);
Console.Write("\t{0}{1}{2}",sub[0], sub[2], sub[1]);
Console.Write("\t{0}{1}{2}",sub[1], sub[2], sub[0]);
Console.WriteLine("\t{0}{1}{2}",sub[2], sub[0], sub[1]);
}
正如@Rawling指出的那样,我们可以进一步概括它以获得字符的索引以获得三个字符。
string word = "hello";
for(int i=0; i<word.Length-2; i++)
for(int j=i+1; j< word.Length-1; j++)
for(int k=j+1; k < word.Length; k++)
{
string sub = string.Format("{0}{1}{2}",word[i], word[j], word[k]);
Console.Write("{0}{1}{2}",sub[0], sub[1], sub[2]);
Console.Write("\t{0}{1}{2}",sub[2], sub[1], sub[0]);
Console.Write("\t{0}{1}{2}",sub[1], sub[0],sub[2]);
Console.Write("\t{0}{1}{2}",sub[0], sub[2], sub[1]);
Console.Write("\t{0}{1}{2}",sub[1], sub[2], sub[0]);
Console.WriteLine("\t{0}{1}{2}",sub[2], sub[0], sub[1]);
}
<强>输出强>
hel leh ehl hle elh lhe
hel leh ehl hle elh lhe
heo oeh eho hoe eoh ohe
hll llh lhl hll llh lhl
hlo olh lho hol loh ohl
hlo olh lho hol loh ohl
ell lle lel ell lle lel
elo ole leo eol loe oel
elo ole leo eol loe oel
llo oll llo lol lol oll
修改强>
您可以进一步概括它以获得三个字母提取词的组合
string word = "hello";
for(int i=0; i<word.Length-2; i++)
for(int j=i+1; j< word.Length-1; j++)
for(int k=j+1; k < word.Length; k++)
{
string sub = string.Format("{0}{1}{2}",word[i], word[j], word[k]);
for(int l=0; l<3;l++)
for(int m=0; m<3;m++)
for(int n=0; n<3;n++)
if(l != m && m != n && l!=n)
Console.Write("\t{0}{1}{2}",sub[l], sub[m], sub[n]);
Console.WriteLine("");
}
<强>输出强>
hel hle ehl elh lhe leh
hel hle ehl elh lhe leh
heo hoe eho eoh ohe oeh
hll hll lhl llh lhl llh
hlo hol lho loh ohl olh
hlo hol lho loh ohl olh
ell ell lel lle lel lle
elo eol leo loe oel ole
elo eol leo loe oel ole
llo lol llo lol oll oll