example/rosettacode: add task balanced_brackets
[nit.git] / examples / rosettacode / balanced_brackets.nit
1 #!/usr/bin/env nit
2 #
3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
5
6 # Task: Balanced brackets
7 # SEE: <http://rosettacode.org/wiki/Balanced_brackets>
8 module balanced_brackets
9
10 # Are `[` and `]` balanced?
11 # Other characters are ignored.
12 #
13 # assert is_balanced("[][[]]")
14 # assert is_balanced("")
15 # assert not is_balanced("[[]")
16 # assert not is_balanced("][][")
17 fun is_balanced(s: String): Bool
18 do
19 var l = 0
20 for x in s.chars do
21 if x == '[' then
22 l += 1
23 else if x == ']' then
24 l -= 1
25 if l < 0 then return false
26 end
27 end
28 return l == 0
29 end
30
31 var n = 3
32 if args.not_empty then n = args.first.to_i
33
34 for i in [0..10[ do
35 var a = (['[', ']'] * n)
36 a.shuffle
37 var b = a.join("")
38 if is_balanced(b) then print "{b} is well-balanced" else print "{b} is not well-balanced"
39 end