下面的代码工作正常。
private int[] list = new int[]{ 3, 5, 10};
private int[] temp = new int[list.length];
public void Generate()
{
for (int a=0;a<list[0];a++)
{
temp[0] = a;
for (int b=0;b<list[1];b++)
{
temp[1] = b;
for (int c=0;c<list[2];c++)
{
temp[2] = c;
int[] asd = temp;
}
}
}
}
但是如果我改变列表数组长度,我必须在里面添加一个for循环。如何为任何大小的列表数组编写一个方法?例如:
private int[] list = new int[]{ 2, 5, 12,18};
代码不起作用!
答案 0 :(得分:2)
我不能100%确定你的函数应该产生什么,但是如果你想在单个函数中等同于你的代码,那么它看起来像这样(假设C#作为语言):< / p>
private int[] list = new int {3, 5, 10};
public void Generate()
{
List<string> toPrint = new List<string>();
string num_string = string.Empty;
string base_string = string.Empty;
for(int i=list.length; i>-1; i--)
{
num_string = num_string + list[i].ToString();
base_string = base_string +'0';
}
lastnumber = Int16.parse(num_string[list.length - 1]);
int string_length = base_string.length;
bool running = true;
while(running)
{
bool finished = true;
for(int incre=0; incre < lastnumber; incre ++)
{
string temp = base_string;
temp[string_length-1] = (char)incre;
toPrint.add(temp);
}
for(int i = 2; i <= base_string.length; i++ )
{
int currentnumber = Int16.Parse(base_string[base_string.length - i]);
int number_limit = Int16.Parse(num_string[base_string.length -i]));
if(currentnumber < number_limit)
{
currentnumber = currentnumber +1;
base_string[base_string.length - i] = (char)currentnumber
finished = false;
break;
}
if(finished)
{
base_string[base_string.length - i] = 0
}
}
if(finished)
{
running = false;
}
}
string [] asd = toPrint.ToArray()
}
这是你在找什么?如果没有,你能提供更多细节,以便我有更好的背景吗?