1

My assignment is to use a random number generator function to get 7 unique integers between 0 and 9, store them in an array, and display the output.

I have tried with this code below, but it fails to give me 7 unique integers. I still receive duplicate values.

Any help is appreciated, thank you.

import java.util.Scanner;

public class JavaProgramCh8Ex2 {

  //Global Scanner object to read input from the user:
  static Scanner keyboard = new Scanner(System.in);

  //Global variable to hold the size of the array:
  final static int SIZE = 7;

  //Main
  public static void main(String[] args) {

    //Populate the array with 7 numbers:
    int [] sevenNumbers = new int [SIZE];
    populateSevenNumbersArray(sevenNumbers);

    //Display the numbers to the user:
    displaySevenNumbers(sevenNumbers);

}


    //Populate the numbers array with 7 random numbers:
    public static void populateSevenNumbersArray (int [] numArray){
      int maxElement;
      for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
        for (int i = 0; i <= (maxElement - 1); i++) {
          numArray[i] = getRandomNumber(0, 9);
          if(numArray[i] == numArray[i + 1]){
            numArray[i + 1] = getRandomNumber(0, 9);
          }
        }
      }
    }


    //Display the numbers to the user:
    public static void displaySevenNumbers (int [] numArray){
      for (int i = 0; i < numArray.length; i++) {
        System.out.print(numArray[i] + " ");
      }
    }


    //Get random numbers to populate the 7 numbers array:
    public static int getRandomNumber(int low, int high){
      return (int)(Math.random() * ((high + 1) - low)) + low;
    }

}
prognatis
  • 33
  • 4
  • 1
    @ScaryWombat This question is not a duplicate of what you specified. Either change the reference or reopen please. – Tim Biegeleisen Nov 11 '16 at 01:15
  • 2
    Here is a solution showing how to achieve what you want http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array especially `List solution = new ArrayList<>(); for (int i = 1; i <= 6; i++) // change to seven { solution.add(i); } Collections.shuffle(solution);` – Scary Wombat Nov 11 '16 at 01:18
  • 1
    A comment about your code. It's good that you chose a constant, and called it `SIZE`. You can change the size any time you like. But no you can't! You've written "seven" into method and variable names! That's as bad as a ["magic number"](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants). Also, instead of writing your own `getRandomNumber`, just use [`Random.nextInt`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-). – Klitos Kyriacou Nov 11 '16 at 01:29

2 Answers2

2

In this code

 numArray[i] = getRandomNumber(0, 9);
 if(numArray[i] == numArray[i + 1]){      // yes you retry here
    numArray[i + 1] = getRandomNumber(0, 9);  // but what about here
 }

maybe a loop would be better

 int num = getRandomNumber(0, 9);
 while( isInArray(num){          // write a method to check
   num = getRandomNumber(0, 9);  
 }
 numArray[i] = num;

But really this is over complicating it when a solution like

List<Integer> solution = new ArrayList<>(); 
for (int i = 0; i < 10; i++) { solution.add(i); }     
Collections.shuffle(solution);

and then take a subset of 7

Integer[] numArray = Arrays.copyOfRange(solution.toArray(new Integer[0]), 0, 6);

and to finish

    for (int x : numArray) {
        System.out.println(x);
    }

Output

9
3
4
6
7
1
8

would work better

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Probably an overkill but I'd like to try solving this using streams.

public final static Random RANDOM = new Random();

/**
 * Random unique integers from a given range [low, high)
 * @param size - number of integers to take, must be less than or equal to high - low
 * @param low - lower bound, inclusive
 * @param high - upper bound, exclusive
 * @return a list of unique, randomly chosen integers from the given range
 * @throws IllegalArgumentException if size is greater than high - low.
 */
public static List<Integer> uniqueSample(int size, int low, int high) {
    if (size > high - low) throw new IllegalArgumentException();
    return Stream.generate(choice(low, high))
            .distinct() // Discard duplicate 
            .limit(size) // Limit the size of the result.
            .collect(Collectors.toList());
}

/**
 * Return a random integer in range [low, high)
 * @param low - lower bound, inclusive
 * @param high - upper bound, exclusive
 * @return a random integer between low and high (exclusive)
 */
private static Supplier<Integer> choice(int low, int high) {
    return ()->low + RANDOM.nextInt(high - low);
}

public static void main(String [] args) {
    uniqueSample(7, 0, 10).forEach(System.out::println);
}

The idea is the same: you keep generating random integers between 0 and 9 until you get one that you have never seen, then add it to the result. Stop when we have 7 such integers.

xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30