首页 > 解决方案 > 在数组中交换随机选择的位置

问题描述

我有一个一维数组[1,2,3,4],我想交换两个随机计算的位置,例如我得到位置 1 和 4。我想要一个看起来像[4,2,3,1] 的新数组。有谁知道如何编程?

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;
    }

标签: java

解决方案


更改位置很容易,认为您的代码中似乎存在一些错误。

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;
    }

推荐阅读