How do I generate a random derangement of a list/array in java?

Jon

I am having trouble implementing a method that returns a random derangement of size n. I am not sure what is wrong with my code, and I need help figuring out what's logically wrong.

This is for a small program I just wanted to write but having trouble visualizing the logic flow. I have tried changing the conditions of the while loop but nothing I tried works so far. I also tried implementing by using a list and arraylist but it became a bit too complex when I tried to put it into code.

Is there a simpler way to do this?

public static int[] derangement(int n){
    int[] arr1 = new int[n];
    int[] arr2 = new int[n];
    //second array is to keep track of which positions are 'taken' to prevent collision
    Random rand = new Random();
    int temp = -1;
    for(int i =0; i <n; i++){
        arr1[i] = i;
    }
    for(int k=0;k<n;k++){
        arr2[k] = -1;
    }
    for(int j=0;j<n;j++){
        temp = j;
        while (temp == j || arr2[j] != -1){
            temp = rand.nextInt(n); //generate a random number until it gives one that hasn't been used before
            if(arr2[temp] == -1){
                arr2[temp] = j;
            }
        }

    }
    return arr2;
}

I expected the output as [2,4,1,5,3,0] for n = 6, but I just get [-1,-1,-1,-1,-1,-1]

MWB

What about using a SortedMap where your keys are going to be random, like this:

public static int[] derangement(int n){
    Random rand = new Random();
    int[] result = new int[n];
    SortedMap<Double, Integer> map = new TreeMap<>();
    for (int i = 0; i < n; i++) {
        map.put(rand.nextDouble(), i);
    }
    int i = 0;
    for (Double key: map.keySet()) {
        result[i] = map.get(key);
        i++;
    }
    return result;
}

This way, as the random keys in your map become ordered, you are shuffling the list.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I generate random sample data in my Oracle database?

How do I generate a random integer between min and max in Java?

How do I generate a random n digit integer in Java using the BigInteger class?

How do I generate a random password in a user's language?

How do I generate discrete random events with a Poisson distribution?

How do I make my Android app generate a random number?

How do I generate a random number in java between 450 and 150 that is a multiple of 10?

How do I generate random numbers in Dart?

How do I generate a random int number?

How do I generate random number for each row in a TSQL Select?

Generate a random derangement of a list

How do I generate random points in 3D space?

How do I generate a vector of random numbers in a range?

How do I generate a random timestamp in the next 5 days in Python?

How do I generate random doubles in an Array?

How do I generate a random num::BigUint?

How do I generate random positions of hexagon using svg?

How do I generate a random color in a specific range?

How do I generate random numbers to fill in empty rows?

How do I generate any random date between 01/01/2016 to 01/01/2017 using Java?

Random derangement memory leak

How do I generate random numbers x times?

How do I generate a primary key that is not random?

How do I generate a list with specified size of random integers within a range in Java 8?

How do I generate multiple random variables in Java?

Python: How do I generate a random matrix of 1.0 and 0.0, but with floats?

how do I generate random group names using lists

How do I generate a random integer in C#?

How do I generate a random number between 1 and 0 in SAS?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive