example/rosettacode: add task balanced_brackets
authorJean Privat <jean@pryen.org>
Tue, 5 May 2015 18:27:57 +0000 (14:27 -0400)
committerJean Privat <jean@pryen.org>
Wed, 6 May 2015 01:28:13 +0000 (21:28 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

examples/rosettacode/balanced_brackets.nit [new file with mode: 0644]
tests/sav/balanced_brackets.res [new file with mode: 0644]

diff --git a/examples/rosettacode/balanced_brackets.nit b/examples/rosettacode/balanced_brackets.nit
new file mode 100644 (file)
index 0000000..a1ae476
--- /dev/null
@@ -0,0 +1,39 @@
+#!/usr/bin/env nit
+#
+# This file is part of NIT ( http://www.nitlanguage.org ).
+# This program is public domain
+
+# Task: Balanced brackets
+# SEE: <http://rosettacode.org/wiki/Balanced_brackets>
+module balanced_brackets
+
+# Are `[` and `]` balanced?
+# Other characters are ignored.
+#
+#     assert is_balanced("[][[]]")
+#     assert is_balanced("")
+#     assert not is_balanced("[[]")
+#     assert not is_balanced("][][")
+fun is_balanced(s: String): Bool
+do
+       var l = 0
+       for x in s.chars do
+               if x == '[' then
+                       l += 1
+               else if x == ']' then
+                       l -= 1
+                       if l < 0 then return false
+               end
+       end
+       return l == 0
+end
+
+var n = 3
+if args.not_empty then n = args.first.to_i
+
+for i in [0..10[ do
+       var a = (['[', ']'] * n)
+       a.shuffle
+       var b = a.join("")
+       if is_balanced(b) then print "{b} is well-balanced" else print "{b} is not well-balanced"
+end
diff --git a/tests/sav/balanced_brackets.res b/tests/sav/balanced_brackets.res
new file mode 100644 (file)
index 0000000..ea08659
--- /dev/null
@@ -0,0 +1,10 @@
+][[]][ is not well-balanced
+[[]][] is well-balanced
+[]][][ is not well-balanced
+[[[]]] is well-balanced
+[][]][ is not well-balanced
+]][[][ is not well-balanced
+[]]][[ is not well-balanced
+[]][][ is not well-balanced
+[][][] is well-balanced
+][]][[ is not well-balanced