java - How can I shuffle an array using a seeded randomiser? - Stack Overflow

I must prompt for a number range and seed, then create an array of 5 numbers per row that has 2 of each

I must prompt for a number range and seed, then create an array of 5 numbers per row that has 2 of each number within the given range, in ASCENDING order. Following this, the order should be shuffled using a seeded randomiser, until all original values have been used.

EDIT (instructions I was given for specifically the last for loop):

  • SEED A RANDOMISER
  • ITERATE OVER THE COLLECTION UNTIL ALL NUMBERS ARE USED
  • RETRIEVE A RANDOM NUMBER TO BE USED AS AN INDEX TO TAKE A VALUE FROM ORIGINAL COLLECTION
  • IF NUMBER DOES NOT EQUAL ZERO PRINT AND MAKE IT EQUAL ZERO

This is the last step in my code but I still receive duplicates of collection values.

I have managed to print the array both times succesfully, however the shuffled values don't match the order given in the Zybooks answers. I assume its something with nextInt but I can't figure out what, as I receive duplicates of the same numbers. For those wondering how there can be a set answer, it is because the randomiser is using a seed, meaning the same seed should yield the same results.

import java.util.Random;
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);System.out.println("Please enter the number of elements to be paired.");
      System.out.println();
      int numPairs = scnr.nextInt();
      
      int[] board = new int[numPairs * 2];
      
      // populate the board
      int num = 1;
      for (int i = 0; i < board.length; i+= 2) {
         board[i] = num;
         board[i + 1] = num;
         num++;
      }
      
      //print initial pairs
      
      for (int i = 0; i < board.length; i++) {
         System.out.printf("%4d", board[i]);
         if ((i + 1) % 5 == 0 || board.length - 1 == i) { 
            System.out.println();
         }
      }
      
      System.out.println();
      
      System.out.println("Please enter a seed number for testing purposes.");
      System.out.println();
      //SEED a randomiser for testing purposes (use the Random class for this).
      int seed = scnr.nextInt();
     
      Random random = new Random();
      random.setSeed(seed);
      
      int remainingElements = board.length;
      for (int i = 0; i < board.length; i++) {
         board[i] = random.nextInt(numPairs) + 1;
         
         if (board[i] != 0) {
            System.out.printf("%4d", board[i]);
            if ((i + 1) % 5 == 0 || board.length - 1 == i) {   
               System.out.println();
               board[i] = 0;
            }
         }
      }
   }
}

I am testing with values 5 and 22, 5 being the number of pairs and 22 being the seed. Expected result is (2 1 1 5 3 4 2 4 3 5), what I receive currently is (4 4 5 3 2 1 3 5 1), again using 5 and 22 as input values. What confuses me most is how I can still receive duplicate numbers despite the if (board[i] != 0) part..

I must prompt for a number range and seed, then create an array of 5 numbers per row that has 2 of each number within the given range, in ASCENDING order. Following this, the order should be shuffled using a seeded randomiser, until all original values have been used.

EDIT (instructions I was given for specifically the last for loop):

  • SEED A RANDOMISER
  • ITERATE OVER THE COLLECTION UNTIL ALL NUMBERS ARE USED
  • RETRIEVE A RANDOM NUMBER TO BE USED AS AN INDEX TO TAKE A VALUE FROM ORIGINAL COLLECTION
  • IF NUMBER DOES NOT EQUAL ZERO PRINT AND MAKE IT EQUAL ZERO

This is the last step in my code but I still receive duplicates of collection values.

I have managed to print the array both times succesfully, however the shuffled values don't match the order given in the Zybooks answers. I assume its something with nextInt but I can't figure out what, as I receive duplicates of the same numbers. For those wondering how there can be a set answer, it is because the randomiser is using a seed, meaning the same seed should yield the same results.

import java.util.Random;
import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);System.out.println("Please enter the number of elements to be paired.");
      System.out.println();
      int numPairs = scnr.nextInt();
      
      int[] board = new int[numPairs * 2];
      
      // populate the board
      int num = 1;
      for (int i = 0; i < board.length; i+= 2) {
         board[i] = num;
         board[i + 1] = num;
         num++;
      }
      
      //print initial pairs
      
      for (int i = 0; i < board.length; i++) {
         System.out.printf("%4d", board[i]);
         if ((i + 1) % 5 == 0 || board.length - 1 == i) { 
            System.out.println();
         }
      }
      
      System.out.println();
      
      System.out.println("Please enter a seed number for testing purposes.");
      System.out.println();
      //SEED a randomiser for testing purposes (use the Random class for this).
      int seed = scnr.nextInt();
     
      Random random = new Random();
      random.setSeed(seed);
      
      int remainingElements = board.length;
      for (int i = 0; i < board.length; i++) {
         board[i] = random.nextInt(numPairs) + 1;
         
         if (board[i] != 0) {
            System.out.printf("%4d", board[i]);
            if ((i + 1) % 5 == 0 || board.length - 1 == i) {   
               System.out.println();
               board[i] = 0;
            }
         }
      }
   }
}

I am testing with values 5 and 22, 5 being the number of pairs and 22 being the seed. Expected result is (2 1 1 5 3 4 2 4 3 5), what I receive currently is (4 4 5 3 2 1 3 5 1), again using 5 and 22 as input values. What confuses me most is how I can still receive duplicate numbers despite the if (board[i] != 0) part..

Share Improve this question edited Mar 25 at 5:51 Anonymous 86.6k15 gold badges162 silver badges178 bronze badges asked Mar 23 at 12:18 pg777pg777 132 bronze badges 13
  • 1 Welcome to Stack Overflow. Please edit your question to include your source code as a working minimal reproducible example, which can be compiled and tested by others to provide an answer faster. Add the output/result you are currently getting and the result you want instead. Explain in detail how the expected result is defined. Also explain what "Zybooks answers" is. – Progman Commented Mar 23 at 13:04
  • 2 @pg777 I wonder, is board[i] = random.nextInt(numPairs) + 1 correct? Seems to me you should be doing something along the lines of randomizing the indexes, not the values. – Slaw Commented Mar 23 at 15:53
  • 1 It is meant to set the bounds of the output to be within the first input value... I feel like this is the problem, as the values aren't being derived from the actual array themselves?? Also I'll point out that my code does return (3 1 3 2 5 5 3 4 2 2) now, not sure if I had changed something before. – pg777 Commented Mar 25 at 6:01
  • 1 @Slaw Bingo! With code very similar to your suggested algorithm I got the expected result, (2 1 1 5 3 4 2 4 3 5). pg777, it’s your turn. – Anonymous Commented Mar 25 at 6:08
  • 1 Just two details wrong: (1) For a random index into the board you need random.nextInt(board.length) instead of random.nextInt(numPairs+1), (2) You subtract 1 from remainingElements no matter if you pick and print an element or not, causing too few numbers to be printed. You should only subtract 1 when a number is printed (causing the loop to run more times than there are elements, but it will terminate after all element have been printed, so it’s fine). – Anonymous Commented Mar 25 at 6:58
 |  Show 8 more comments

1 Answer 1

Reset to default 1

As has been said in the comments by @Slaw and @Anonymous:

The algorithm that your teacher is after is (partly pseudocode):

// Iterate until all numbers have been used
while (remainingElements > 0) {
    // Retrieve a random number to be used as an index
    // to take a value from original collection
    int i = <random index>;
    // If number does not equal zero, print and make it equal to zero
    if (board[i] != 0) {
        print board[i];
        board[i] = 0;
        remainingElements--;
    }
}

For picking a random index into your board you need to use random.nextInt(board.length).

Notice that we only decrease remainingElements when a number is picked and printed, not every time through the loop. This causes the loop to repeat more times than there are elements in the board array. Eventually the random index will also pick the last remaining elements, remainingElements will be decreased to 0 and the loop will terminate.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744287046a4566848.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信