Node[][] nd = new Node[80][30]; Node[] result = new Node[10]; Random r = new Random(); int i ,j; for(int n = 0; n < 10; i++) { i = r.nextInt(78) + 1; j = r.nextInt(28) + 1; Node nod = Node[i][j]; int m; for(m = 0; m < result.length; m++) { if(result[m] == nod) break; } if(m == result.length) result[n] = nod; }没经过测试
int rows = 80, cols = 30; Random r = new Random(); for (int i = 0; i < 10; i++) { int colIndex = r.nextInt(cols - 2) + 1; int rowIndex = r.nextInt(rows - 2) + 1; System.out.println("选中节点:[" + rowIndex + "][" + colIndex + "]"); } 输出: 选中节点:[59][28] 选中节点:[62][26] 选中节点:[10][3] 选中节点:[2][26] 选中节点:[55][13] 选中节点:[21][2] 选中节点:[59][18] 选中节点:[70][20] 选中节点:[15][16] 选中节点:[20][23]
假设你已经会了:
List<int> getSumble(int count,int int start,int end){
List<int> ret=new List<int>();
while(ret.length<count)
{
//生成一个在start和end之间的随机数i;
if(!ret.Contains(i))
{
ret.add(i);
}
}
return ret;
}
Node[][] nd = new Node[80][30];
Node[] result = new Node[10];
Random r = new Random();
int i ,j;
for(int n = 0; n < 10; i++) {
i = r.nextInt(78) + 1;
j = r.nextInt(28) + 1;
Node nod = Node[i][j];
int m;
for(m = 0; m < result.length; m++) {
if(result[m] == nod)
break;
}
if(m == result.length)
result[n] = nod;
}没经过测试
for (int i = 0; i < 10; i++) {
int colIndex = r.nextInt(cols - 2) + 1;
int rowIndex = r.nextInt(rows - 2) + 1;
System.out.println("选中节点:[" + rowIndex + "][" + colIndex + "]");
}
输出:
选中节点:[59][28]
选中节点:[62][26]
选中节点:[10][3]
选中节点:[2][26]
选中节点:[55][13]
选中节点:[21][2]
选中节点:[59][18]
选中节点:[70][20]
选中节点:[15][16]
选中节点:[20][23]
为了保证不重复,可以:
办法一:把产生过的(i,j)保存在java.awt.Point中,把Point放到一Set中,当Set.siz()==10时结束。
办法二:设一个boolean[80][30]标志数组,产生过的对应的位置设为true,新产生的随机点,不能是true