dimanche 12 mars 2023

Issues with seed value output of randomized values Java

I am trying to build a program in java that a user inserts a value and with the numbers up to that value, a seed is used to pseudo-randomize the table of values. For example, if the user inputs 5, the program creates a 5x5 table that has every number up until one duplicated e.g

this is the example

After this, the table should be pseudo-randomized by another value the user is prompted to enter. My issue is that the values that are being randomized are incorrect, as per the below image where the numbers range from 1-5. as the user inputted 5,and is pseudo-randomized by the seed value of 22. Can someone please help? Thank you.

Output of my program versus expected output

This is my code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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.");
        int input = scnr.nextInt();
        // Initialize a 1D Array
        int i = 0;
        // Append duplicates of pair values 1-input 
        List<Integer> pairs = new ArrayList<>();
        for (i = 1; i <= input; i++) {
            // Adds value twice to the array
            pairs.add(i);
            pairs.add(i);
        }

    // Prints pairs into a table and creates a new line every fifth value
    int count = pairs.size();
    int newLine = 0;
    for (i = 0; i < count; i++) {
        int pair = pairs.get(i);
        System.out.printf("%4d", pair);
        System.out.print("");
        newLine = newLine + 1;

        if (newLine == 5) {
            System.out.println("");
            // Reset lineCount back to 0 to allow for new calc to occur
            newLine = 0;
        }
    }
    System.out.println();

    System.out.println("Please enter a seed number for testing purposes.\n");
    int seed = scnr.nextInt();
   // Collections.shuffle(pairs, new java.util.Random(seed));
   Random randomGeneratorName = new Random(seed);

    // Print the pairs in a table with a max of 5 numbers per row
    count = pairs.size();
    newLine = 0;
    int[] usedNumbers = new int[input];
    int unusedNumbers = input * 2;
    for (i = 0; i < count; i++) {
        int index = pairs.get(i) - 1; // change index to start at 0
        int number = index + 1; // change number to start at 1
        if (usedNumbers[index] == 0) {
            System.out.printf("%4d", number);
            usedNumbers[index] = 1;
            unusedNumbers--;
            newLine++;
            if (newLine == 5) {
                System.out.println();
                newLine = 0;
            }
        }
    }
    System.out.println();

}

}




Aucun commentaire:

Enregistrer un commentaire