Java - Randomize Numbers In Interval

List the Randomized Numbers In Interval

Description

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.

Test cases

You can use the following test cases to verify your code logics.

ID Input Ouput
11,7 5 3 4 7 1 2 6
23, 66 4 3 5
3-5, 6 5 0 2 -3 -2 3 -1 4 -4 1 6 -5

Code template

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
  }
}

Answer

Here is the answer to the question above.

Demo

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();
  }
}

Related Quiz