如何在 java 中打印具有特定长度的数组子集
how to print subsets of an array with a specific length in java
我想打印数组长度为 n 和子集长度为 k 的数组的子集。
例如,你有 {1,2,3} 并且你必须在不同的行中打印 {1,2} {1,3} {2,3} 并排序。(另外你必须在之前打印 {1,2} {1,3})
我在网上搜索过,但他们使用的是不允许的数组列表。
如果有人能帮助解决这个问题,我将不胜感激。
在 main 中,我们对数组进行排序并调用名为 loopy_loop 的递归方法。如果这对您来说是新标准,您也可以在这里要求自定义排序。
public static void main(String[] args) {
int[] source = {0,8,2,3,1,9,5,6,4,7};
int k = 3, n = 10;
int[] destination = new int[k];
// first the sorting
Arrays.sort(source);
for (int i = 0; i < n; i++)
System.out.print(source[i] + " ");
System.out.println();
if (k > 0)
loopy_loop(source, destination, 0, 0);
}
这是一个递归函数。 level 跟随 (int)k 的值并且决定了在 destination[] 中要填充的位置以及递归的 "depth"。
public static void loopy_loop(int[] source, int[] destination, int level, int startIndex) {
for (int i = startIndex; i < source.length - destination.length + level + 1; i++) {
destination[level] = source[i];
if (level == destination.length - 1)
{
String rez = String.valueOf(destination[0]);
for (int j = 1; j < destination.length; j++)
rez += ", " + destination[j];
System.out.println("{"+ rez +"}");
}
else
loopy_loop(source, destination, level + 1, i + 1);
}
}
我想打印数组长度为 n 和子集长度为 k 的数组的子集。 例如,你有 {1,2,3} 并且你必须在不同的行中打印 {1,2} {1,3} {2,3} 并排序。(另外你必须在之前打印 {1,2} {1,3}) 我在网上搜索过,但他们使用的是不允许的数组列表。 如果有人能帮助解决这个问题,我将不胜感激。
在 main 中,我们对数组进行排序并调用名为 loopy_loop 的递归方法。如果这对您来说是新标准,您也可以在这里要求自定义排序。
public static void main(String[] args) {
int[] source = {0,8,2,3,1,9,5,6,4,7};
int k = 3, n = 10;
int[] destination = new int[k];
// first the sorting
Arrays.sort(source);
for (int i = 0; i < n; i++)
System.out.print(source[i] + " ");
System.out.println();
if (k > 0)
loopy_loop(source, destination, 0, 0);
}
这是一个递归函数。 level 跟随 (int)k 的值并且决定了在 destination[] 中要填充的位置以及递归的 "depth"。
public static void loopy_loop(int[] source, int[] destination, int level, int startIndex) {
for (int i = startIndex; i < source.length - destination.length + level + 1; i++) {
destination[level] = source[i];
if (level == destination.length - 1)
{
String rez = String.valueOf(destination[0]);
for (int j = 1; j < destination.length; j++)
rez += ", " + destination[j];
System.out.println("{"+ rez +"}");
}
else
loopy_loop(source, destination, level + 1, i + 1);
}
}