jeudi 7 mars 2019

Storing Random Generated Numbers in an Array in Java

Write a method called generateSecretDigits() that takes as input an integer and returns an array of integers containing the 4 digits that make up the randomly generated secret number. The method uses the input to create an object of type Random with the provided seed. The method then uses such object to generate a random integer between 0 and 9 (both included). If the integer is not already part of the array, then the method uses it to initialize one of the elements of the array, otherwise a new integer is generated. The process continues until all four elements of the array have been generated. This allows us to generate an array containing four digits that are all different from one another. Make sure to initialize the elements of the array from the first one to the last one.

For example:

  • generateSecretDigits(123) returns the array {2, 0, 6, 9}
  • generateSecretDigits(45) returns the array {9, 1, 0, 7}
  • generateSecretDigits(987) returns the array {5, 8, 9, 7}

Here's what I have done so far:

import java.util.Random;

public class BullsAndCows {

public static void main (String[] args) {

// A method that checks if an element is contained within a given array

public static boolean contains(int[] listOfElements, int element) {

// Declare and initialize a variable

boolean elementPresent = false;

// Loop through all the elements in the array

for (int i = 0; i < listOfElements.length; i++) {

  // Check if an element is contained within the array

  if (element == listOfElements[i]) {

    elementPresent = true;

    return elementPresent;
  }
}

return elementPresent;

}

// A method that randomly generates a secret 4-digits number

public static int[] generateSecretDigits(int x) {

// Declare and initialize an array

int[] secretDigits = new int[4];

// Generate a number between 0 and 9 inclusively with the provided seed

int seed = x;
Random digit = new Random(seed);

for (int i = 0; i < 4; i++) {

  int secret = digit.nextInt(9);

  // Assign a value to each element of the array

  if (contains(secretDigits, secret) == false) {

    secretDigits[i] =  secret;
  }

  else {

    i--;
  }
}

return secretDigits;

}




Aucun commentaire:

Enregistrer un commentaire