For question 4 you will have to use a random number generator.
In Java, you can generate a random number in the following way.
First, you have to import the Random class
import java.util.Random;
Second, at the top of your method in which you want to use a random number, you should write
Random rand = new Random();
Now, every time you want to get a random integer between 0 (counting 0) and maxInt (not counting maxInt), you can write
rand.nextInt(maxInt);
For example, to generate 100 numbers between 0 and 100 and print them, you could write:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random rand = new Random(); //at the beginning, only call this once
for (int i=0; i < 100; i++) {
//inside a for loop so called many times
System.out.println(rand.nextInt(100));
}
}
}
A useful link on Random numbers in Java is below:
http://java.about.com/od/javautil/a/randomnumbers.htm
The goal of the question is to generate a random permutation. What this means is that the method should return an array with (in the case of English alphabet) 26 letters in it
The index of each element of the array will correspond with the letter "from" and the value in the array will be the value "to" The counting starts from 0 since arrays start from 0.
So we'll think of A as the 0th letter and B as the 1st letter.
For example, if the array had values:
1,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
It would mean, the 0th letter (i.e. A) maps to the 1st letter (i.e. B)
The goal in this question is to generate a random mapping. The mapping has to be one-to-one. That is, you should not have 2 letters mapping to the same letter. If A maps to B, then nothing else should map to B.
There are 2 ways to do this. Either is acceptable for the assignment.
1)Go through each letter, starting from 0 and assign a randomInt. At each step, to do this, you must generate a random int using rand.nextInt(26). You then should check that the int has not already been chosen.
As an example, you could randomly choose a number between 0 and 26 to assign A to. Then randomly choose a number between 0 and 26 to assign B to. You must verify that A has not already been assigned the same letter.
Then randomly choose a number to assign C to. You must check that neither A nor B has been assigned this letter. And so on
2)The second way to do it is perhaps simpler. First start out with something that you KNOW is a one-to-one mapping. This mapping could be, for example, every letter mapping to itself.
Now, choose TWO random numbers between 0 and 26 and swap the values of the array at those indices. Repeat this operation a large amount of times (like 10000 times).
This second approach amounts to "shuffling" the permutation. At the end, it will be a random permuation.
You can do either approach. Method 2 is perhaps a bit easier.