Created
November 13, 2017 02:30
-
-
Save agrawal-priyank/fa4180eee22e633fad4acd8ad3fb804c to your computer and use it in GitHub Desktop.
Boolean Parenthesizaton by Dynamic Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooleanParenthesizaton { | |
public static void main (String args[]) { | |
char[] symbol = {'T', 'T', 'F', 'T'}; | |
har[] operator = {'|', '&', '^'}; | |
BooleanParenthesizaton bP = new BooleanParenthesizaton(); | |
System.out.println(bP.countWaysToParenthesize(symbol, operator)); | |
} | |
public int countWaysToParenthesize(char[] symbol, char[] operator) { | |
if(symbol == null || symbol.length == 0 || operator == null || operator.length == 0 | |
|| symbol.length - 1 != operator.length){ | |
return -1; | |
} | |
int n = symbol.length; | |
int[][] T = new int[n][n]; | |
int[][] F = new int[n][n]; | |
for(int i = 0; i < n; i++){ | |
T[i][i] = symbol[i] == 'T' ? 1 : 0; | |
F[i][i] = symbol[i] == 'F' ? 1 : 0; | |
} | |
for(int len = 2; len <= n; len++){ | |
for(int i = 0; i <= n - len; i++){ | |
int j = i + len - 1; | |
T[i][j] = F[i][j] = 0; | |
for(int gap = 0; gap < len - 1; gap++){ | |
int k = i + gap; | |
int totalIK = T[i][k] + F[i][k]; | |
int totalKJ = T[k + 1][j] + F[k + 1][j]; | |
if(operator[k] == '&'){ | |
T[i][j] += T[i][k] * T[k + 1][j]; | |
F[i][j] += totalIK * totalKJ - T[i][k] * T[k + 1][j]; | |
} else if(operator[k] == '|'){ | |
T[i][j] += totalIK * totalKJ - F[i][k] * F[k + 1][j]; | |
F[i][j] += F[i][k] * F[k + 1][j]; | |
} else{ // operator is ^ | |
T[i][j] += T[i][k] * F[k + 1][j] + F[i][k] * T[k + 1][j]; | |
F[i][j] += T[i][k] * T[k + 1][j] + F[i][k] * F[k + 1][j]; | |
} | |
} | |
} | |
} | |
return T[0][n - 1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment