簡體   English   中英

創建隨機布爾值的特定2D數組

[英]Creating a specific 2D array of random Boolean values

我目前正在編寫一個程序,該程序將在給定大小的情況下創建一個2D布爾矩陣。 我需要在隨機對象中使用種子來創建將由網格構成的true / false值。 假值應由-表示,真值應由#表示。 我目前無法使用種子制作真/假值網格,而且我不確定如何用指定的字符表示真/假值。

這就是我當前的代碼。

import java.util.Arrays;
import java.util.Random;

public class Life {

public static void main(String [] args) {
    int rows = 6;
    int columns = 8;
    Random rand = new Random();
    rand.setSeed(7);
    boolean[][]matrix = new boolean[rows][columns];

    for (int row = 0; row < matrix.length; row++ ) {
        for (int col = 0; col < matrix[row].length; col++) {

            matrix[row][col] = rand.nextBoolean();

            System.out.print(matrix[row][col] + "\t");

        }
    }
}
}

我目前的結果如下:

true    true    true    false   false   false   true    true    true    true    false   true    false   false   true    true    false   true    true    false   true    false   true    true    true    true    false   true    false   true    false   true    true    true    false   true    false   true    true    true    false   true    false   false   true    true    false   true

全部都是一條直線,而不是6 x 8的網格。

我想說的是這樣的

- = - - = - = -
= - - = - = - -
- - = - - = - = 
- = - - = - = -
= - = - - = - -
- - - = = - - =

首先,您需要根據數組中的值來決定要打印哪個字符。 這可以通過三元運算符完成:

System.out.print((matrix[row][col] ? "=" : "-") + " "); // a space is fine, you don't need a tab.

然后,您需要在外部for循環的每次迭代結束時額外打印一行,因為外部for循環是打印行的代碼。

您的循環應如下所示:

for (int row = 0; row < matrix.length; row++ ) {
    for (int col = 0; col < matrix[row].length; col++) {

        matrix[row][col] = rand.nextBoolean();

        System.out.print((matrix[row][col] ? "=" : "-") + " ");

    }
    System.out.println();
}

有關更簡單的解決方案,請參見@Sweeper的答案。

您也可以使用流來執行此操作:

String matrix = IntStream.range(rows)
    .mapToObj(i -> IntStream.range(columns)
        .mapToObj(j -> rand.nextBoolean())
        .map(b -> b? "=" : "-")
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")))

我將使用一個enum來表示單元格,您可以使用兩個可能的值(分別表示“ TRUE”和“ FALSE”狀態)來創建它,該函數將boolean值映射到正確的值並覆蓋toString()以便於打印。 喜歡,

static enum Cell {
    FALSE, TRUE;
    public static Cell fromBoolean(boolean a) {
        if (a) {
            return TRUE;
        }
        return FALSE;
    }

    @Override
    public String toString() {
        if (this == TRUE) {
            return "=";
        }
        return "-";
    }
}

現在,您的main方法可以將布爾值從matrix轉換為Cellprint出來;

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        if (col != 0) {
            System.out.print(' ');
        }
        matrix[row][col] = rand.nextBoolean();
        System.out.print(Cell.fromBoolean(matrix[row][col]));
    }
    System.out.println();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM