我使用 ArrayList 编写了关于 1 到 10 之间随机排列的简单代码。如何在我的文件 SmartPermutationGenerator 中制作 ArrayList 以在控制台中按 10 的大小打印结果以获得如下输出:
我不想要这个输出:
使用 Smart Force 的随机数组:
8 4 8 1 8 4 10 8 4 1 7 8 4 1 10 5 8 4 1 10 7 2 8 4 1 10 7 5 9 8 4 1 10 7 5 2 6 8 4 1 10 7 5 2 9 3 8 4 1 10 7 5 2 9 6 6 6
我想要这个输出:
使用 Smart Force 的随机数组:
8 4 8 1 8 4 10 8 4 1
7 8 4 1 10 5 8 4 1 10
7 2 8 4 1 10 7 5 9 8
4 1 10 7 5 2 6 8 4 1
10 7 5 2 9 3 8 4 1 10
7 5 2 9 6
应该限制仅使用数组列表的解决方案,不想使用递归。
这是我的文件 SmartPermutationGenerator
import java.util.ArrayList;
import java.util.Random;
public class SmartPermutationGenerator
{
private int size;
private Random rand = new Random();
public SmartPermutationGenerator()
{
this.size = 10;
}
public ArrayList nextPermutation()
{
ArrayList<Integer> unused = new ArrayList<Integer>();
for (int i = 0; i < size; i++) // loop for element in array
{
unused.add(i + 1);
}
ArrayList<Integer> perm = new ArrayList<Integer>();
for (int k = 0; k < size; k++) //loop for random number between 1 to 10
{
int pos = rand.nextInt(unused.size());
perm.add(unused.get(pos));
unused.remove(pos);
System.out.print(perm.get(k) + " ");
for (int j = 0; j < k; j++)
{
System.out.print(perm.get(j) + " "); //loop for permutation 10 times
//System.out.println();
}
}
return perm;
}
}
这是我的文件 BrutePermutationGenerator
import java.util.Random;
public class BrutePermutationGenerator
{
private int[] num = new int[10];
public int[] nextPermutation()
{
Random rand = new Random();
for (int j = 0; j < 10; j++)//loop for permutation 10 times
{
for (int i = 0; i < 10; i++)//loop for random number between 1 to 10
{
int low = 1;
int high = 10;
int range = high - low + 1;
int r = rand.nextInt(range);
num[i] = num[r];
num[r] = i;
}
for (int i = 0; i < 10; i++)// loop for element in array
{
System.out.print(num[i] + 1 + " ");
}
System.out.println();
}
return num;
}
}
这是我的主文件 PermutationGeneratorViewer
public class PermutationGeneratorViewer
{
public static void main(String[] args)
{
BrutePermutationGenerator brute = new BrutePermutationGenerator();
SmartPermutationGenerator smart = new SmartPermutationGenerator();
System.out.println("\n" + "Random arrays using Brute Force: ");
brute.nextPermutation();
System.out.println("\n" + "Random arrays using Smart Force: ");
smart.nextPermutation();
}
}
最佳答案
您可以在打印循环中使用模运算符 (%) 来查看索引是否是 10 的倍数。如果是,则打印换行符。 像这样的事情会起作用:
for(...){
System.out.print(...);
if(count%10==0 && count!=0){ // if the index of the number is a multiple of 10 but not the first number
System.out.println(); // print a newline to separate rows
}
}
这将在第 10、20、30 等数字后添加换行符。
关于java - 使用 ArrayList<Integer> 进行排列,在控制台中按 10 的大小打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941589/