面试, 碰到这么一个古怪笔试题, 花了10分钟才看懂题目, 要了两张草稿纸也没作出来, 汗!无脸见人! 大家来讨论一下
题目: 将一个交错数据合并为一个一维数组
输入: strJaggedArray[][], 由多个一维数组(长度不定,个数不定)组成的交错数组
输出: strArray[], 由strJaggedArray[r][c]中的元素以"&"为分隔符拼合而成, 是strJaggedArray中数组元素的无重复组合(不考虑顺序)
举例:
输入: strJaggedArray[0]=new string[] {"we","are","student"};
strJaggedArray[1]=new string[] {"say","what"};
输出: strArray[]={"we&say","we&what","are&say","are&what","student&say","student&what"}
输入: strJaggedArray[0]=new string[] {"cs","app"};
strJaggedArray[1]=new string[] {"good","cool","dev"};
strJaggedArray[2]=new string[] {"king","of","the","world"};
输出: strArray[]={"cs&good&king","cs&good&of","cs&good&the","cs&good&world","cs&cool&king","cs&cool&of","cs&cool&the","cs&cool&world",...}
答案:
string[][] a = new string [3][];
a[0] = new string[] { "cs", "app" };
a[1] = new string[] { "good", "cool", "dev" };
a[2] = new string[] { "king", "of", "the", "world" };
System.Collections.ArrayList arrlist = new System.Collections.ArrayList();
int[] index = new int[a.Length];
while (index[0] < a[0].Length)
{
string temp = "";
for (int i = 0; i < index.Length; i++)
{
temp += a[i][index[i]] + "&";
}
arrlist.Add(temp.Substring(0, temp.Length-1));
index[index.Length - 1]++;
for (int i = index.Length - 1; i > 0; i--)
{
if (index[i] >= a[i].Length)
{
index[i] = 0;
index[i - 1]++;
}
}
}
Array b = arrlist.ToArray(typeof(string));