added midterm preparation

This commit is contained in:
2025-03-25 15:20:23 +01:00
parent 8c01471dda
commit eebfe377c7
4 changed files with 88 additions and 0 deletions

20
src/MidTermPrep1/Ex2.sc Normal file
View File

@@ -0,0 +1,20 @@
import scala.annotation.tailrec
def balanceMatch(chars: List[Char]): Boolean = {
@tailrec
def checkStep(chars: List[Char], n: Int): Boolean = {
if (chars.isEmpty) n == 0
else if (n < 0) false
else checkStep(chars.tail, chars.head match {
case '(' => n + 1
case ')' => n - 1
case _ => n
})
}
checkStep(chars, 0)
}
balanceMatch("(if (x == 0) then max (1, x))".toList)
balanceMatch("I told him (that it's not (yet) done). (But he wasn't listening)".toList)
balanceMatch(")".toList)
balanceMatch("())()".toList)