import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author René Moll (188084), Philipp Mehlhorn (188308) * */ public class Truthtable { static ArrayList array = new ArrayList(); static int counter = 0; private static void printTruthTable(int n) { //stopwatch start time double zstVorher = System.currentTimeMillis(); n *= 2; int rows = (int) Math.pow(2, n); String tempString = ""; // main for-loop. calculates every possible combination with Ds and Us for a specific length for (int i = 0; i < rows; i++) { for (int j = n - 1; j >= 0; j--) { // turns it into binary int temp = i / (int) Math.pow(2, j) % 2; // converts it into Ds and Us and saves it into a temporary string tempString = tempString.concat((temp == 1) ? "U" : "D"); } // every temporary string gets sent to the checkstring method to get checked if (tempString != "") checkString(tempString); tempString = ""; } for (String s : array) { System.out.println(s); } //stopwatch end time double zstNachher = System.currentTimeMillis(); System.out.println("\nZeit benötigt: " + ((zstNachher - zstVorher)) + " msec oder " + ((zstNachher - zstVorher) / 1000) + " Sekunden"); System.out.println(counter + " Möglichkeiten für n=" + n / 2 + " (" + n + " Stellen)"); } // checks the string for the rules that the excercise gave us public static void checkString(String s) { if ((s.contains("DUDUDU") && (countDUDU(s, "DUDU") <= 1)) || (((countDUDU(s, "DUDU") == 2)) && !(s.contains("DUDUDU")))) { if (s.startsWith("U") && s.endsWith("D")) { if (checkAmountDU(s)) { if (countDUDU(s, "D") == countDUDU(s, "U")) { //if the path fullfills every rule, than it gets saved in an string array counter++; array.add(s); } } } } } /** * Counts the amount of search patterns in a string * @param s the string that should be checked * @param search the search pattern, that will be counted * @return amount of the search string value in the string */ public static int countDUDU(String s, String search) { Pattern p = Pattern.compile(search); Matcher m = p.matcher(s); int count = 0; while (m.find()) { count += 1; } return count; } /** * @param s a DU path to check * @return boolean true,if there are always more or equal Us than Ds */ public static boolean checkAmountDU(String s) { for (int i = 1; i <= s.length(); i++) { if (!(countDUDU(s.substring(0, i), "D") <= countDUDU(s.substring(0, i), "U"))) { return false; } } return true; } public static void main(String[] args) { // hier dein tatsächliches n angeben ! (n=5 hat 3 Möglichkeiten und 10 Stellen z.B.) printTruthTable(15); } }