Balanced brackets: Difference between revisions

Content added Content deleted
(→‎{{header|D}}: link to doc on the built-in)
Line 268: Line 268:
'[[[[]][]]][[][]]' is balanced
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced</lang>
'][[][[]]][]]][[[[]' is not balanced</lang>

=={{header|Ruby}}==
{{trans|D}}
{{works with|Ruby|1.9}}
<lang ruby>re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
\g<bb>* # zero or more <bb>
\] # literal ]
)* # end group, zero or more such groups
\z/x # end of string

(0..9).each do |i|
s = "[]" * i

# Knuth shuffle
(s.length - 1).downto(1) do |a, b|
b = rand(a + 1)
s[a], s[b] = s[b], s[a]
end

puts((s =~ re ? " OK: " : "bad: ") << s)
end

["[[]", "[]]", "[letters]"].each do |s|
puts((s =~ re ? " OK: " : "bad: ") << s)
end</lang>

One output: <pre> OK:
OK: []
bad: ][][
bad: ]][[][
bad: ]][[][[]
bad: ]][[[[]][]
bad: ][][]]][[[[]
OK: [[]][[[]]][][]
bad: [[][][][]]][[][]
bad: []]][]][[][[[][][]
bad: [[]
bad: []]
bad: [letters]</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==