Cappuccino90 icon

Dyck Pfad Algorithmus v3.0

Cappuccino90 | PRO | 10/06/15 07:08:20 PM UTC | 0 ⭐ | 224 👁️ | Never ⏰ | []
Java |

1.95 KB

|

None

|

0 👍

/

0 👎

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Truthtable {
    static ArrayList<String> array = new ArrayList<String>();
    static int counter = 0;
 
    private static void printTruthTable(int n) {
        double zstVorher = System.currentTimeMillis();
        n *= 2;
 
        int rows = (int) Math.pow(2, n);
 
        String tempString = "";
 
        for (int i = 0; i < rows; i++) {
            for (int j = n - 1; j >= 0; j--) {
 
                int temp = i / (int) Math.pow(2, j) % 2;
 
                tempString = tempString.concat((temp == 1) ? "U" : "D");
            }
            if (tempString != "")
                checkString(tempString);
            tempString = "";
        }
 
        for (String s : array) {
            System.out.println(s);
        }
 
        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)");
    }
 
    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")) {
                        counter++;
                        array.add(s);
                    }
                }
            }
        }
    }
 
    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;
    }
 
    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 z.B.)
        printTruthTable(9);
    }
 
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎