Advertisement
Guest User

HTW Berlin Web Technology Scala Balanced improved -ESS

a guest
May 26th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. object Balanced {
  2. def main(args: Array[String]) {
  3. val s1: String = "((a))"
  4. val s2: String = "a - )())()x("
  5. println(balanced(s1.toList))
  6. println(balanced(s2.toList))
  7. }
  8. def balanced (s: List[Char]): Boolean ={
  9. def countChar(l: List[Char], count: Int, s: Char): Int = {
  10. if (l.isEmpty) count
  11. else {
  12. if (s == l.head) countChar(l.tail, count + 1, s)
  13. else countChar(l.tail, count, s)
  14. }
  15. }
  16. def check (s: List[Char], c: Int): Boolean= {
  17. if (s.isEmpty && c == 0) true
  18. else if( s.isEmpty && c != 0) false
  19. else if(s.head == '(') check(s.tail, c +1)
  20. else if (s.head == ')' && c >0) check(s.tail, c -1)
  21. else check(s.tail, c)
  22. }
  23. if (countChar(s, 0, '(') == countChar(s, 0, ')')) check(s, 0)
  24. else false
  25.  
  26. }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement