Guest User

Untitled

a guest
Jan 22nd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. function balanced($string) {
  2. return isBalanced($string, "");
  3. }
  4.  
  5. function isBalanced($chars, $stack) {
  6. if (!strlen($chars))
  7. return empty($stack);
  8.  
  9. switch ($chars[0]) {
  10. case '(':
  11. // prepend stack with '(', move to next character
  12. return isBalanced(substr($chars, 1), $chars[0] . $stack);
  13. case ')':
  14. // if '(' seen previously, shift stack, move to next character
  15. return !empty($stack) && isBalanced(substr($chars, 1), substr($stack, 1));
  16. default:
  17. // do nothing to stack, move to next character
  18. return isBalanced(substr($chars, 1), $stack);
  19. }
  20. }
  21.  
  22. object Main {
  23. def balance(chars: List[Char]): Boolean = {
  24. def balanced(chars: List[Char], stack: String): Boolean = {
  25. if (chars.isEmpty)
  26. stack.isEmpty
  27. else if (chars.head == ')')
  28. balanced(chars.tail, chars.head + stack)
  29. else if (chars.head == '(')
  30. !stack.isEmpty && balanced(chars.tail, stack.tail)
  31. else
  32. balanced(chars.tail, stack)
  33. }
  34.  
  35. balanced(chars, "")
  36. }
  37. }
  38.  
  39. balance("(if (0) false (x))".toList) - fails
  40. balance("profit and loss (P&L).n(cashflow)".toList) - fails
  41. balance(":)".toList) - passes
  42. balance(")(()".toList) - passes
  43.  
  44. def balance(chars: List[Char]): Boolean = {
  45. @tailrec def balanced(chars: List[Char], open: Int): Boolean =
  46. chars match {
  47. case Nil => open == 0
  48. case '(' :: t => balanced(t, open + 1)
  49. case ')' :: t => open > 0 && balanced(t, open - 1)
  50. case _ :: t => balanced(t, open)
  51. }
  52.  
  53. balanced(chars, 0)
  54. }
  55.  
  56. def balance(chars: List[Char]): Boolean = chars.foldLeft(0){
  57. case (0, ')') => return false
  58. case (x, ')') => x - 1
  59. case (x, '(') => x + 1
  60. case (x, _ ) => x
  61. } == 0
  62.  
  63. def balance(chars: List[Char]): Boolean =
  64. doBalance(chars, 0) == 0;
  65. def doBalance(chars: List[Char], parenthesisOpenCount: Int): Int =
  66. if(parenthesisOpenCount <0) -100;
  67. else
  68. if(chars.isEmpty) parenthesisOpenCount
  69. else
  70. chars.head match {
  71. case '(' => return doBalance(chars.tail, parenthesisOpenCount+1)
  72. case ')' => return doBalance(chars.tail, parenthesisOpenCount-1)
  73. case _ => return doBalance(chars.tail, parenthesisOpenCount)
  74. }
Add Comment
Please, Sign In to add comment