紧急求救一个算法
例如下列的字符串
"user1,user2 ", "add1,add2 ", "tel1,tel2 "
要得到所有可能的组合
user1,add1,tel1;
user1,add1,tel2;
user1,add2,tel1;
user1,add2,tel2;
user2,add1,tel1;
user2,add1,tel2;
user2,add2,tel1;
user2,add2,tel2;
请教各位,在JAVA中该怎么做这个算法呢?实在太急了,想了几个小时没有想出来,请大家帮忙,多谢了。
[解决办法]
不难啊,没有java,用vb试了下。
Dim strString1(2) As String
Dim strString2(2) As String
Dim strString3(2) As String
strString1(0) = "A1 "
strString1(1) = "A2 "
strString2(0) = "B1 "
strString2(1) = "B2 "
strString3(0) = "C1 "
strString3(1) = "C2 "
For i As Integer = 0 To 1
For j As Integer = 0 To 1
For k As Integer = 0 To 1
System.Console.WriteLine(strString1(i) + ", " + strString2(j) + ", " + strString3(k) + "; ")
Next
Next
Next
[解决办法]
public class ExchangeArray {
/**
* @Auth Red_angelX
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[][] strJaggedArray = new String[3][];
strJaggedArray[0] = new String[] { "user1 ", "user2 "};
strJaggedArray[1] = new String[] { "add1 ", "add2 "};
strJaggedArray[2] = new String[] { "tel1 ", "tel2 "};
String[] strArray = Exchange(strJaggedArray);
for(int i=0; i < strArray.length ;i++)
{
System.out.println(strArray[i]);
}
}
/**
* 函数
* @param strJaggedArray
* @return
*/
public static String[] Exchange(String[][] strJaggedArray)
{
String[][] temp = DoExchange(strJaggedArray);
return temp[0];
}
/**
* 递归
* @param strJaggedArray
* @return
*/
private static String[][] DoExchange(String[][] strJaggedArray)
{
int len = strJaggedArray.length;
if(len > = 2)
{
int len1 = strJaggedArray[0].length;
int len2 = strJaggedArray[1].length;
int newlen = len1*len2;
String[] temp = new String[newlen];
int Index = 0;
for(int i=0;i <len1;i++)
{
for(int j=0;j <len2;j++)
{
temp[Index] = strJaggedArray[0][i] + ", "+strJaggedArray[1][j];
Index ++;
}
}
String[][] newArray = new String[len-1][];
for(int i=2;i <len;i++)
{
newArray[i-1] = strJaggedArray[i];
}
newArray[0] = temp;
return DoExchange(newArray);
}
else
{
return strJaggedArray;
}
}
}