java - Java 获取 10 个布尔值并随机化它们
问题描述
这是我的第一篇文章,如果我做错了什么,请见谅!
我正在尝试制作一个程序,您可以在其中输入宽度和高度。从这 2 个值中,取其中的 10 个并将这 10 个值随机设置为真或假。顺便说一句,这是我一直遇到问题的学校作业。
我该怎么做呢?
这是给我的问题:
任务1:
- 创建新类“BinaryMap”
- 创建新方法“generateRandomArrayFix”,它创建一个 10x10 大小的 2D 布尔数组
- 用 false 初始化所有值
- 100 个值中的 10 个应随机更改为 true
- 返回您的布尔数组。
import java.util.Random;
import Prog1Tools.IOTools;
public class BinaryMap {
public static void main(String[] args) {
boolean[][] array = generateRandomArray();
// for (int i = 0; i < array.length; i++) {
// printArray(array[i]);
// }
}
private static void printArray(boolean[] booleans) {
}
/**
* Ändert einen Wert im gegebenen daten-Array;
* aus wahr wird falsch und aus falsch wird wahr
*
* @param daten - Array welches verändert werden soll
* @param x - x-Koordinate des Wertes
* @param y - y-Koordinate des Wertes
*/
static void updateArray(boolean[][] daten, int x, int y) {
}
private static boolean[][] generateRandomArrayFix() {
// Random rand = new Random();
/*
* 10 random aus 100
*/
boolean[][] randomArray;
int x = 10, y = 10;
randomArray = new boolean[x][y];
for (x = 0; x < randomArray.length; x++) {
for (y = 0; y < randomArray.length; y++) {
randomArray[x][y] = false;
}
}
return randomArray;
}
private static boolean[][] generateRandomArray() {
Random rand = new Random();
int rowWidth = IOTools.readInt("Enter Grid Width: ");
int colHeight = IOTools.readInt("Enter Grid Height: ");
boolean[][] board = new boolean[rowWidth][colHeight];
for (int idx = 1; idx <= 10; ++idx) {
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextBoolean();
}
}
//display output
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
return board;
}
return board;
}
}
解决方案
欢迎来到 SO。不幸的是,您发布的代码存在很多问题(包括语法错误),因此我们很难提出具体的更改来解决您的问题。
我建议您先将任务分解为几个步骤,然后将每个步骤转换为您验证的方法(通过单元测试),而不是为需求提供解决方案,然后再进行下一个步骤。
因此,例如,第一个任务是:创建一个 10x10 数组,初始化为 false。为此编写测试可能是唯一棘手的部分。就像是:
class BinaryMap {
public int countValues(boolean value) {
...
}
}
class BinaryMapTest {
@Test
void testInitialisation() {
BinaryMap map = new BinaryMap():
assertThat(map.countValues(false)).isEqualTo(100);
assertThat(map.countValues(true)).isEqualTo(0);
}
}
true
我建议您在继续随机分配值之前让该代码正常工作。
在这种情况下,真正要避免的唯一棘手的事情就是生成 10 个随机位置并将它们分配给true
. true
如果您碰巧生成重复项,则数组中的值将少于 10 个。
所以而不是:
for 10 iterations
assign random value to true
你需要
while there are less than 10 true values
assign random value to true
推荐阅读
- file-upload - 查看上传的文件 symfony4
- asp.net - 我需要一个接一个地通过 30 秒的时间延迟向 5 个联系人发送邮件
- python - 异常训练 Resnet50:“输入到“Flatten”的形状未完全定义”
- jenkins - 手动 gerrit 审查 cmd 未更新“已验证”标签值
- python - 如何加快我的 python 程序
- julia - 在 Julia 中重新分配对象数组中的值
- vba - 用不同名称保存同名附件
- sql-server - 创建函数来替换字符串查询会减慢存储过程
- json - Angular5 嵌套 JSON 到 Excel 转换
- sql-server - 为什么我在下面的查询中收到错误?