Created
September 23, 2017 20:53
-
-
Save Erezbiox1/8f37febf3f4873dc4ffb18712db6e892 to your computer and use it in GitHub Desktop.
Complex Boolean Statement Parser
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
fun analyze(statement: String) : Boolean { | |
var string = statement | |
if(statement.contains('(')){ | |
var start = 0 | |
var end = statement.length - 1 | |
for ((index, letter) in statement.toCharArray().withIndex()) { | |
if(letter == '(') { | |
start = index | |
break | |
} | |
} | |
val array = statement.toCharArray() | |
while(end != 0){ | |
if(array[end] == ')') | |
break | |
end-- | |
} | |
string = statement.substring(0, start) + analyze(statement.substring(start + 1, end)) + statement.substring(end + 1) | |
} | |
while(string.contains("!")) { | |
string = string.replaceAll("!true", "false") | |
string = string.replaceAll("!false", "true") | |
} | |
while(string.contains("||")) { | |
string = string.replaceAll("true||false", "true") | |
string = string.replaceAll("false||true", "true") | |
string = string.replaceAll("true||true", "true") | |
string = string.replaceAll("false||false", "false") | |
} | |
while(string.contains("&&")) { | |
string = string.replaceAll("true&&false", "false") | |
string = string.replaceAll("false&&true", "false") | |
string = string.replaceAll("true&&true", "true") | |
string = string.replaceAll("false&&false", "false") | |
} | |
return string.toBoolean() | |
} | |
fun String.replaceAll(replaceWhat: String, replaceWith: String) = this.replace(Pattern.quote(replaceWhat).toRegex(), replaceWith) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment