我在通过用户给出的标准设置数组时遇到了麻烦,其中数组必须由三个字符设置; X,O和"空白"。
用户将输入一个数组是X和O的多少(他们只是简单地说一个的百分比给另一个,因为他们等于"以及多少数组将为空。 然后通过该输入,我认为那里应该是一个循环,它不断使用Math.random()函数来协调一个随机值,直到达到其中一个字符的最大数量为&#39 ; ll继续循环,但调整math.random()给出的值,使其自动重定向到不同的字符。
至少,这是我希望能有效的想法。出于某种原因,我所采取的每一个裂缝只会产生空白细胞和O-占据细胞;没有X。
这是算法的主要部分。
int itemsX = (int) (n*n*(percentX/100));
int itemsBlank = (int) (n*n*(percentBlank/100));
int itemsO = (n*n) - (itemsBlank + itemsX);
// Now we construct the grid.
for (i = 0; i < n; i++) {
for ( j = 0; j< n; j++) {
double q = Math.random();
// In this first set of If/Else's, the program will
// use a random number generator to place our items.
if (q >= .66 && a < itemsBlank) {
tissue[i][j] = ' ';
a = a + 1;
// In the event the Program has used up all of one particular item in a grid before finishing,
//it will redirect the randomized value to a different item to be put in place.
}if (q >= .66 && a == itemsBlank){
q = q - .33; }
if (q < .66 && q >= .33 && b < itemsO) {
tissue[i][j] = 'O';
b = b + 1;
if (q <.66 && q >= .33 && b == itemsO)
{ q = q - .33;
}if (q < .33 && c < itemsX) {
tissue[i][j] = 'X';
c = c + 1;
}if (q < .33 && c == itemsX)
{q = q + .66; }
}
System.out.print(tissue[i][j]);
}
}System.out.println();
}
这是代码的介绍部分,要求输入,声明等。但是,我不确定问题是否存在于此处。
System.out.println("Input the side length of the grid to begin setting up the parameters for the grid.");
int n = IO.readInt();
System.out.println("Input the threshold (required surrounding cells for given satisfaction)");
double threshold = IO.readDouble();
if(threshold < 0){
System.out.println("Threshold must be a greater than 0.");
IO.reportBadInput();
}
System.out.println("Enter the maximum rounds the program should calculate for an agent to be satisfied");
int maxRounds = IO.readInt();
if(maxRounds < 0 ){
System.out.println("Maxrounds should be greater than 0.");
IO.reportBadInput();
}
System.out.println("Input how frequently the program should print the board during rounds of calculation (i.e. How many rounds should the program compute before printing)");
int frequency = IO.readInt();
System.out.println("Input the percent of X and O agents (will be same for both)");
int percentX = IO.readInt();
System.out.println("Input the percentage of blank cells");
int percentBlank = IO.readInt();
if(percentX * 2 + percentBlank > 100 || percentX * 2 + percentBlank < 100){
System.out.println("Percentage does not add up to 100%.");
IO.reportBadInput();
}
char[][] tissue;
tissue = new char[n][n];
int i;
int j;
int a = 0;
int b = 0;
int c = 0;
对此有任何帮助将不胜感激。我从阅读问题以及询问数据的过程中学到了很多关于数组的基础知识,但是我还没有在数组的随机字符分配中找到很多条目。