我试图通过命令行参数接受一些整数,然后从这组数字中生成所有可能的有序集。以下代码执行此操作,但它重复了有序集。
例如,我输入“2 3 4”作为命令行输入,输出如下。
2 3 4
3 2 4
4 3 2
3 2 4
2 3 4
2 4 3
4 3 2
2 4 3
2 3 4
我不想重复有序集。为此,我尝试将整数数组转换为String并仅在未使用Equals方法重复时才打印它。所以,当我使用Array.toString(b)
时,我希望返回一个转换为字符串的整数,但它返回了9个地址。
我的问题是:
我的代码如下:
class Shuffler
{
void swapWith(int[] a,int m,int n,int sizeOfArray)
{
int[] b = new int[sizeOfArray];
b = a.clone();
int temp = b[n];
b[n] = b[m];
b[m]=temp;
for(int k=0;k<sizeOfArray;k++)
{System.out.print(" "+b[k]);}
System.out.println("");
}
public static void main(String[] args)
{
int a[] = new int[10];
Shuffler SH = new Shuffler();
for(int i=0;i<args.length;i++)
{
a[i] = Integer.parseInt(args[i]);
}
System.out.println("Possibilities are..");
for(int k=0;k<args.length;k++)
{
for(int j=0;j<args.length;j++)
{
SH.swapWith(a,k,j,args.length);
}
}
}
}
答案 0 :(得分:1)
您需要做的是实现一些已知的算法,该算法生成集合的所有排列。例如,您可以熟悉并实现这一个。
http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
因此给定字符串“2 3 4”,首先将其拆分为3个字符串“2”,“3”,“4”。然后只需实现一些算法,生成给定集合的所有排列。
另见。
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
答案 1 :(得分:0)
使用我前一段时间实现的一些类:
UnmodifiableLinkedList
- 具有常量LinkedList
函数的addAll()
(java.util.LinkedList
类在线性时间内实现addAll()
),不支持删除元素从列表中(虽然我有一个扩展,它增加了支持);和PermutatableLinkedList
,其中包含Steinhaus-Johnson-Trotter排列算法的实现,以生成列表的所有可能排列。导入的文件全部来自https://github.com/MT-0/Permutations。
import com.github.MT_0.permutations.PermutableUnmodifiableLinkList;
import com.github.MT_0.permutations.UnmodifiableLinkList;
public class Answer {
public static void main(String[] args) {
final PermutableUnmodifiableLinkList<Integer> permutableList = new PermutableUnmodifiableLinkList<Integer>();
for ( String str : args )
{
permutableList.addTail( Integer.parseInt( str ) );
}
final long numPermutations = permutableList.getTotalPermutations();
for ( long i = 0; i < numPermutations; ++i )
{
final UnmodifiableLinkList<Integer> permutation = permutableList.getPermutation();
for ( Integer element : permutation )
System.out.print( element + " ");
System.out.println();
permutableList.nextPermutation();
}
}
}