## 怎么实现随机1-9？

vcxiaohan 发布于 2016/03/10 21:08

2

1

0

```import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {
List<Integer> list = rand();
System.out.println(list);
}

public static List<Integer> rand() {
final Integer[] EXISTED = new Integer[9];
int successCount = 0;
List<Integer> numbers = new ArrayList<>(); // output
while (successCount < 9) {
int rand = (int) (Math.random() * 10 % 9 + 1); // 1-9
Integer value = EXISTED[rand - 1]; // bound 0-8
if (value == null) {
EXISTED[rand - 1] = rand;
successCount += 1;
}
}
return numbers;
}
}```

v

0
v

#### 引用来自“无脑仔的小明”的评论

function getRandomNum(len) {

var arrA = [];
var arrX = [];
var arr = [];
for(var m=0; m<len; m++) {
var res = false;
var ran = Math.ceil(Math.random()*len);

while(!res) {
var x = 1;

console.log('ran'+ran);
for(var i=0; i<arrA.length; i++) {
if(ran != arrA[i]) {
arrX[i] = 1;
}else {
arrX[i] = 0;
}
}

console.log('arrX'+arrX);
for(var j=0; j<arrX.length; j++) {
x *= arrX[j];
}
if(x) {
res = true;
arrA.push(ran);
console.log('a');
}else {
ran = Math.ceil(Math.random()*len);
console.log('b');

}

}
}
return arrA;
}

console.log(getRandomNum(20));
0
:joy::joy:弄个数组呀，选中哪个把哪个删掉扔另一个数组里，当一个数组空了，另一个满了:joy::joy:
0

JS其实和Java差不多的。

```function rand() {
var EXISTED = [null,null,null,null,null,null,null,null,null];
var successCount = 0;
var numbers = new Array();
while(successCount < 9) {
var rand = Math.floor( Math.random() * 10 % 9 + 1 ); // 正确的@！
var value = EXISTED[rand - 1];
if(value == null) {
EXISTED[rand - 1] = rand;
successCount += 1;
numbers.push(rand);
}
}
return numbers;
}
// run test
var numbers = rand();
console.debug(numbers.join(','));```

Math.round() 函数不可以， 请改为Math.ceil( Math.random() * 10 % 9 + 1 ); 否则都产生出10 的数字了。
0
```var _col=[1,2,3,4,5,6,7,8,9];
function main() {
var list = _col.concat();
var total = 20;
for(var i = 0; i < total; i++) {
if(list.length == 0) {
list = _col.concat();
}
var num = Math.floor(Math.random()*list.length);
console.log(list[num]);
list.splice(num,1);
console.log(list);
}
}```

0

N
python笑而不语
0

0