List the Randomized Numbers In Interval
List the Randomized Numbers In Interval
For example, if the range is from 1 to 5, the list of random numbers could be numbers between 1 and 5.
You can use the following test cases to verify your code logics.
ID | Input | Ouput |
---|---|---|
1 | 1,7 | 5 3 4 7 1 2 6 |
2 | 3, 6 | 6 4 3 5 |
3 | -5, 6 | 5 0 2 -3 -2 3 -1 4 -4 1 6 -5 |
Cut and paste the following code snippet to start solve this problem.
import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { test(1, 7); test(3, 6); test(-5, 6); } public static void test(int number1, int number2) { //your code here } }
Here is the answer to the question above.
import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { test(1, 7);/*from w w w. j av a2s . c o m*/ test(3, 6); test(-5, 6); } public static void test(int number1, int number2) { int difference, minNumb = 0; Random rand = new Random(); difference = Math.abs(number1 - number2) + 1; minNumb = number1 >= number2 ? number2 : number1; List<Integer> intNumbers = new ArrayList<>(); while (intNumbers.size() < difference) { int randNumb = rand.nextInt(difference) + minNumb; if (intNumbers.contains(randNumb)) { continue; } else { intNumbers.add(randNumb); } } for (int item : intNumbers) { System.out.print(item + " "); } System.out.println(); } }