如何构建并存储符合指定格式的布尔型真值表二维数组
Fixing Your Truth Table Generation Logic
Hey there! I see you want to generate a truth table where each variable column cycles through standard binary (false/true) combinations, with the final S column initialized to all false. Let's tweak your code to make that happen exactly as you want.
The Issue with Your Current Code
Right now, you’re setting every element in the variable columns to true, which doesn’t create the alternating binary patterns you need. We need to generate sequences where each variable column flips between false and true at specific intervals based on its position.
Modified Working Code
Here’s the adjusted code that produces your desired output:
import java.util.Arrays; public class TruthTableGenerator { public static void main(String[] args) { int nbrVariables = 2; // Adjust this number for more/less variables int nbrCombinaisons = (int) Math.pow(2, nbrVariables); // Initialize truth table: [total rows][variables + S column] boolean tt[][] = new boolean[nbrCombinaisons][nbrVariables + 1]; // First, set the final S column to all false for (int i = 0; i < nbrCombinaisons; i++) { tt[i][nbrVariables] = false; } // Populate variable columns with binary combinations for (int j = 0; j < nbrVariables; j++) { // Calculate how many times a value repeats before flipping int cycleLength = (int) Math.pow(2, nbrVariables - j - 1); for (int i = 0; i < nbrCombinaisons; i++) { // Flip value every cycleLength rows tt[i][j] = (i / cycleLength) % 2 == 1; } } // Print the formatted truth table for (boolean[] row : tt) { String[] rowText = Arrays.stream(row) .map(b -> b ? "True" : "False") .toArray(String[]::new); System.out.println(String.join(" ", rowText)); } } }
How This Logic Works
- Calculate Total Rows: We use
Math.pow(2, nbrVariables)to get the total number of combinations (since each variable has 2 possible values). - Initialize S Column: We explicitly set the last column (index
nbrVariables) to allfalseupfront. - Variable Column Patterns:
- For each variable column
j, we calculate acycleLength— this is how many times the same value repeats before flipping to the other. For example, with 2 variables, the first column has a cycle of 2 (false, false, true, true), and the second column has a cycle of 1 (false, true, false, true). - For each row
i, we check if(i / cycleLength) % 2equals 1. If yes, the value istrue; otherwise, it’sfalse— this creates the perfect alternating binary sequence.
- For each variable column
- Clean Output: We convert boolean values to "True"/"False" strings and join them with spaces to match your desired format.
Example Output (for 2 variables)
False False False False True False True False False True True False
内容的提问来源于stack exchange,提问作者user7110366
相关产品推荐
相关产品推荐

