java - 在数组中交换随机选择的位置
问题描述
我有一个一维数组[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;
}
解决方案
更改位置很容易,认为您的代码中似乎存在一些错误。
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;
}
推荐阅读
- c# - MVVM 轻量级 SimpleIoc
- python-3.x - 两个函数之间的切线
- kubernetes - 升级 aip-server 以使用 etcdv3 api 后 etcdctl 得到很多垃圾信息
- java - 无法使用 OpenBlueDragon CFML 初始化类
- sql-server-2008 - 在 SQL 2008 表中查找缺失的序列号
- java - Elasticsearch:在不使用 JAVA_HOME 的情况下设置 Java 版本
- java - 如何解决 JFRAME 无响应
- node.js - 猫鼬填充时缺少架构错误
- sql - 在sql中查找变量在另一个变量的级别之间的比例
- html - 我可以只使用引导组件而不是布局系统吗