added midterm preparation
This commit is contained in:
20
src/MidTermPrep1/Ex2.sc
Normal file
20
src/MidTermPrep1/Ex2.sc
Normal 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)
|
||||
Reference in New Issue
Block a user