Пользователь вводит строку, например:
true || !false && !true || false
Программа должна вернуть в textView результат этого выражения - true или false. Как это можно реализовать?
Вот то что я пока сделал
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.expressionEditText.addTextChangedListener {
if (it?.toString().isNullOrBlank()) {
val expression = Expression(it.toString())
val table = getTable(expression)
processTable(expression, table)
}
}
getTable(Expression("A B C"))
}
private fun getTable(expression: Expression): List<List<Boolean>> {
val table = mutableListOf<MutableList<Boolean>>()
val numberOfLogicVariables = expression.logicVariables.size
val rows = 2.pow(numberOfLogicVariables)
for (i in 0 until rows) {
val current = i.toString(2).addZero(numberOfLogicVariables)
table.add(mutableListOf())
val row = table[i]
for (j in 0 until numberOfLogicVariables) {
row.add(current[j].digitToInt().toBoolean())
}
}
return table
}
}
fun String.replace(target: CharSequence, replacement: CharSequence): String? {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this
).replaceAll(Matcher.quoteReplacement(replacement.toString()))
}
fun Int.pow(n: Int): Int {
var result = 1
repeat(n) {
result *= this
}
return result
}
@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.SOURCE)
@IntDef(0, 1)
annotation class LogicValues
fun @LogicValues Int.toBoolean() = this != 0
fun String?.notNull() = this ?: ""
fun String.addZero(requiredLength: Int) = "0".repeat(requiredLength - length) + this
infix fun Boolean.implication(other: Boolean) = !this || other
class Expression(private var value: String) {
val logicVariables: List<Char> get() {
val listOfVariables = mutableListOf<Char>()
value.forEach {
if (it in 'A'..'Z' && it !in listOfVariables)
listOfVariables.add(it)
}
return listOfVariables
}
init {
value = value.replace("->", "implication").notNull()
}
}