Balanced brackets: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: improved generator)
Line 955: Line 955:


import (
import (
"bytes"
"fmt"
"fmt"
"math/rand"
"math/rand"
"strings"
"time"
"time"
)
)
Line 966: Line 966:


func generate(n uint) string {
func generate(n uint) string {
nb := strings.Repeat("[]", int(n))
a := bytes.Repeat([]byte("[]"), int(n))
px := rand.Perm(int(2 * n))
for i := len(a) - 1; i >= 1; i-- {
pb := make([]byte, 2*n)
j := rand.Intn(i + 1)
for i := uint(0); i < 2*n; i++ {
a[i], a[j] = a[j], a[i]
pb[i] = nb[px[i]]
}
}
return string(pb)
return string(a)
}
}


Line 984: Line 983:
case ']':
case ']':
if open == 0 {
if open == 0 {
fmt.Println("NOT OK")
fmt.Println("not ok")
return
return


Line 990: Line 989:
open--
open--
default:
default:
fmt.Println("Unexpected content. Generator fail?")
fmt.Println("not ok")
return
return
}
}
}
}
if open == 0 {
if open == 0 {
fmt.Println("OK")
fmt.Println("ok")
} else {
} else {
fmt.Println("NOT OK")
fmt.Println("not ok")
}
}
}
}


func main() {
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 10; i++ {
for i := uint(0); i < 10; i++ {
testBalanced(generate(i))
testBalanced(generate(i))
Line 1,009: Line 1,009:
Output:
Output:
<pre>
<pre>
: OK
: ok
[]: OK
][: not ok
][][: NOT OK
]][[: not ok
[]]][[: NOT OK
[[][]]: ok
[]]]][[[: NOT OK
[][[][]]: ok
]][]][[[][: NOT OK
[[[][][]]]: ok
[[][[[][]]]]: OK
]][[]]][[[[]: not ok
[[]][][[[]]][]: OK
]][[[]][[][[]]: not ok
[[[][[]][]]][][]: OK
[[[[[]]][]]][]][: not ok
[[]]]][][][][[]][[: NOT OK
[][[][[]][][[][]]]: ok
(): not ok
(): Unexpected content. Generator fail?
</pre>
</pre>