Exemple #1
0
  /**
   * Construct a truth table from the given collection of Boolean expressions.
   *
   * @param expressionCollection the collection of Boolean expressions for which to construct this
   *     truth table
   * @throws ParseException if any of the Boolean expressions is not properly formatted
   */
  public TruthTable(final Collection<BooleanExpression> expressionCollection)
      throws ParseException {
    this.expressionCollection = expressionCollection;
    results = new HashMap<Map<String, Boolean>, Map<BooleanExpression, Boolean>>();

    variablesList = new ArrayList<String>();

    for (final BooleanExpression expression : expressionCollection) {
      for (final String str : expression.getVariableSet()) {
        if (!variablesList.contains(str)) {
          variablesList.add(str);
        }
      }
    }

    Collections.sort(variablesList);
    resultsKeyList = buildDictionary(variablesList);

    for (final Map<String, Boolean> dict : resultsKeyList) {
      final Map<BooleanExpression, Boolean> map = new HashMap<BooleanExpression, Boolean>();

      for (final BooleanExpression expression : expressionCollection) {
        map.put(expression, expression.evaluate(dict));
      }

      results.put(dict, map);
    }
  }
Exemple #2
0
  /**
   * Return a string representation of this truth table.
   *
   * @return a string representation of this truth table
   */
  @Override
  public String toString() {
    String str = "";

    // Build the header by listing all variables...
    for (final String var : variablesList) {
      str += var + " ";
    }

    // and then the expressions themselves
    for (final BooleanExpression expression : expressionCollection) {
      str += " " + expression + " ";
    }

    str += "\n";

    // Build each row by listing the values of the variables and the value
    // of the expression
    for (final Map<String, Boolean> dict : resultsKeyList) {
      for (final String var : variablesList) {
        str += (dict.get(var) ? "1" : "0") + " ";
      }

      for (final BooleanExpression expression : expressionCollection) {
        for (int i = 0; i < (expression.toString().length() - 1) / 2; i++) {
          str += " ";
        }

        str += " " + (results.get(dict).get(expression) ? "1" : "0");

        for (int i = 0; i < expression.toString().length() / 2; i++) {
          str += " ";
        }

        str += " ";
      }

      str += "\n";
    }

    str = str.substring(0, str.length() - 1);

    return str;
  }