我正在解决一个问题,我试图获取一定百分比的字符并使用Math.random在5x5数组中随机填充它们以在2d数组中存储25个项目。我现在想出了这个,但我不明白为什么它不能填充我想要的字符。它只是在做' X'它也不是随机的,它看起来与X的总数一致。我试图输出一定百分比的X,O&O以及剩下的东西是空白的。它只输出10个X并且它们似乎不是随机的。我很感激任何建议,我可以了解为什么会发生这种情况。
public static void main(String []args){
char [][] tissue = new char [5][5];
assignCellTypes(tissue,40,40);
}
public static void assignCellTypes(char[][] tissue,int percentO, int percentX){
double cellx=0.0;
double cellO=0.0;
double totalO=0;
double totalX = 0;
totalO = (double)percentO/100;
totalX = (double)
percentX/100;
cellx = totalX *(tissue.length*tissue.length);
cellO = totalO *(tissue.length*tissue.length);
int i;
int j ;
for(int row = 0;row<tissue.length;row++){
for(int col = 0;col<tissue[row].length;col++){
if(cellx>0){
i = (int)Math.floor(Math.random()*tissue.length);
j = (int)Math.floor(Math.random()*tissue.length);
tissue[i][j] = 'X';
System.out.print(tissue[i][j] + " ");
cellx--;
if(cellO>0 && tissue[i][j] != 'X' ){
i = (int)Math.floor(Math.random()*tissue.length);
j = (int)Math.floor(Math.random()*tissue.length);
tissue[i][j] = 'O';
System.out.print(tissue[i][j] + " ");
cellO--;
if(tissue[i][j] != 'X' && tissue[i][j] != 'O'){
tissue[i][j] = ' ';
System.out.print(tissue[i][j] + " ");
}
}
}
}
System.out.println();
}
}
}
答案 0 :(得分:0)
我并不完全知道你想要实现的目标,但似乎你只是想用X
和O
随机填充一个字符数组,并在此案例有一个更简单的解决方案
public static void assignCellTypes(char[][] tissue, int percentO, int percentX)
{
double chanceO = percentO / (double) ( percentO + percentX );
Random r = new Random(); //java.util.Random
for(int i=0; i < tissue.length; i++)
for(int j=0; j < tissue[i].length; j++)
if( r.nextDouble() <= chanceO )
tissue[i][j] = 'O';
else
tissue[i][j] = 'X';
}
编辑@comment,我认为这是你想要实现的目标:
public static void assignCellTypes(char[][] tissue, int percentO, int percentX)
{
if(percentO + percentX > 100)
throw new Exception("You can't have more than 100%!");
double chanceO = percentO/100d;
double chanceX = percentX/100d;
Random r = new Random(); //java.util.Random
for(int i=0; i < tissue.length; i++)
for(int j=0; j < tissue[i].length; j++)
{
double random = r.nextDouble();
if( random <= chanceO )
tissue[i][j] = 'O';
else if( random <= chanceO + chanceX )
tissue[i][j] = 'X';
}
}