I wrote a simple program using int[]
and ArrayList<Integer>
which aims to get a random permutation output between 1 to 10, where each number will not be repeated in each line of output (each line of output will have number 1 until 10 in a different order). Both classes work nicely with the desire output. Is there any other possible way to shorten my code?
Random arrays using brute force:
3 5 2 9 7 8 10 1 4 6
4 10 5 2 3 9 6 1 7 8
7 9 1 10 3 8 5 4 2 6
5 3 8 9 10 2 6 7 1 4
8 5 9 7 10 6 4 2 1 3
4 10 2 9 8 6 3 7 5 1
8 9 10 2 5 4 6 7 3 1
7 2 4 9 5 10 6 8 1 3
9 2 8 1 10 7 6 4 5 3
8 1 10 3 9 7 4 2 5 6
This is my BrutePermutationGenerator file:
import java.util.Random;
public class BrutePermutationGenerator
{
public int[] getRandomPermutation()
{
Random rand = new Random();
int[] array = new int[10];
int r = 0;
int count = 0;
boolean fill;
int low = 1;
int high = 10;
int range = high - low + 1;
do
{
fill = true;
r = rand.nextInt(10) + 1;
for (int i = 0; i < array.length; i++)//loop for random number between 1 to 10
{
if (array[i] == r)
{
fill = false;
}
}
if (fill == true)
{
array[count] = r;
count++;
}
}
while (count < 10);
for (int i = 0; i < array.length; i++)//loop for element in array
{
System.out.print(array[i] + " ");
}
return array;
}
public void nextPermutation()
{
for (int i = 0; i < 10; i++) //loop for permutation 10 times
{
getRandomPermutation();
System.out.println();
}
}
}
This is my SmartPermutationGenerator file:
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<Integer> getRandomPermutation()
{
ArrayList<Integer> unused = new ArrayList<>();
for (int i = 0; i < size; i++) // loop for element in array
{
unused.add(i + 1);
}
ArrayList<Integer> perm = new ArrayList<>();
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);
}
return perm;
}
public void nextPermutation()
{
for(int i = 0; i < size; i++) //loop for permutation 10 times
{
for(Integer item : getRandomPermutation())
{
System.out.print(item + " ");
}
System.out.println();
}
}
}
This is my PermutationGeneratorViewer file:
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();
}
}