Balanced brackets: Difference between revisions
Go solution
(→{{header|JavaScript}}: Added a Lua example.) |
(Go solution) |
||
Line 724:
[][[]] OK
[] OK</pre>
=={{header|Go}}==
<lang go>package main
import (
"fmt"
"rand"
"strings"
"time"
)
func init() {
rand.Seed(time.Nanoseconds())
}
func generate(n uint) string {
nb := strings.Repeat("[]", int(n))
px := rand.Perm(int(2 * n))
pb := make([]byte, 2*n)
for i := uint(0); i < 2*n; i++ {
pb[i] = nb[px[i]]
}
return string(pb)
}
func testBalanced(s string) {
fmt.Printf("%s: ", s)
var open int
for i := 0; i < len(s); i++ {
switch s[i] {
case '[':
open++
case ']':
if open == 0 {
fmt.Println("NOT OK")
return
}
open--
default:
panic("Unexpected content. Generator fail?")
}
}
if open == 0 {
fmt.Println("OK")
} else {
fmt.Println("NOT OK")
}
}
func main() {
for i := uint(0); i < 10; i++ {
testBalanced(generate(i))
}
testBalanced("()")
}</lang>
Output:
<pre>
: OK
][: NOT OK
[][]: OK
][[][]: NOT OK
[[][][]]: OK
]][][][][[: NOT OK
][][][]][[[]: NOT OK
[[]][]]][][[[]: NOT OK
]][[[][][][][][]: NOT OK
][]]]][[[]][[[]][[: NOT OK
(): panic: Unexpected content. Generator fail?
</pre>
=={{header|Haskell}}==
|