Swap in an array the places which were randomly selected

Tags:



I have a one-dimensional array [1,2,3,4] and I want to swap two random calculated positions, for example I get position 1 and 4. I want to have a new array that looks like [4,2,3,1]. Does anyone have an idea how to program this?

int[] test = new int[] {1,2,3,4}
int random1;
int random2;
while(true) {
      random1 = getRandomNumber(initalOffer.length, 1);
      random2 = getRandomNumber(initalOffer.length, 1);
}

// change Position random1 with random2 
int[] newArray = new int[test.length];
for(int i=0; i < test.length; i++) {
   if (i == random1) {
       newArray [random1] = test[random2];
   }
   else {
       newArray [i] = test[i];
   }
   
}

private int getRandomNumber(int max, int min) {
        int number = (int) (Math.random() * max) + min;
        return number;
    }

Answer

Change positions is easy, thought it seems there’s a couple of bugs in your code.

int[] test = new int[] {1,2,3,4}
int random1;
int random2;

// This is wrong: can you explain why are you doing this? It will never finish.
// Also: array position starts in 0, not 1. Try testing with 0.
while(true) {
      random1 = getRandomNumber(initalOffer.length, 1);
      random2 = getRandomNumber(initalOffer.length, 1);
}

// change Position random1 with random2, easy in only 4 lines of code:
int randValue1 = test[random1];
int randValue2 = test[random2];
test[random1] = randValue2;
test[random2] = randValue1;

private int getRandomNumber(int max, int min) {
        int number = (int) (Math.random() * max) + min;
        return number;
    }


Source: stackoverflow