Balanced brackets: Difference between revisions

Added uBasic/4tH version
imported>Thebeez
(Added uBasic/4tH version)
 
(32 intermediate revisions by 18 users not shown)
Line 176:
19 [[[[[[][[[[[][][ ?
20 [[][[][] ?
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program balencebrac64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Expression : "
szMessBalenced: .asciz " balanced"
szMessNotBalenced: .asciz " not balanced"
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24 // conversion buffer
sBuffer: .skip 80
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
mov x0,0b111000 // bit 1 = open bracket bit 0 = close bracket
bl testBalanced
 
mov x0,0b110100
bl testBalanced
mov x0,0b11001001
bl testBalanced
mov x19,10 // number random test
1:
mov x0,1 // mini number
mov x1,10000 // maxi random number
bl extRandom // generate random number
bl testBalanced
subs x19,x19,1
bge 1b
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrszMessNotBalenced: .quad szMessNotBalenced
qAdrszMessBalenced: .quad szMessBalenced
qAdrszMessStart: .quad szMessStart
qAdrsBuffer: .quad sBuffer
/***************************************************/
/* routine to test expression */
/***************************************************/
/* x0 expression */
testBalanced:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
ldr x1,qAdrsBuffer
bl isBalanced
cmp x0,0
ldr x3,qAdrszMessNotBalenced
ldr x4,qAdrszMessBalenced
csel x3,x3,x4,eq
 
mov x0,#4 // string number to display
ldr x1,qAdrszMessResult
ldr x2,qAdrsBuffer
ldr x4,qAdrszCarriageReturn
bl displayStrings // display message
100:
ldp x2,x3,[sp],16 // restaur registres
ldp x1,lr,[sp],16 // restaur registres
ret
/***************************************************/
/* control if expression is balenced */
/***************************************************/
/* x0 expression */
/* x1 buffer address */
/* x0 return 1 if balanced else zero */
isBalanced:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x3,63
clz x2,x0 // number of zeros on the left
sub x2,x3,x2 // so many useful numbers right
mov x4,1 // mask to test bit
lsl x4,x4,x2 // shift left begin expression
mov x3,0 // top if right bracket > left bracket
mov x7,0 // indice display buffer expression
mov x5,0 // counter brackets
1: // begin loop to test bits
tst x0,x4
beq 2f // bit = 0
mov x6,'(' // else bit = 1 -> open bracket
strb w6,[x1,x7] // store in buffer
add x7,x7,1 // increment indice
add x5,x5,1 // increment open bracket
b 3f
2: // bit = 0
mov x6,')' // close bracket
strb w6,[x1,x7] // store in buffer
add x7,x7,1 // increment indice
subs x5,x5,1 // decrement open bracket
bge 3f // if negative
mov x3,1 // top error
3:
lsr x4,x4,1 // shift mask right
cbnz x4,1b // and loop if not zero
strb wzr,[x1,x7] // zero final on buffer
cmp x5,0 // right bracket <> left bracket -> error
bne 4f
cmp x3,0 // in expression left bracket > right bracket
bne 4f
mov x0,1 // balanced
b 100f
4:
mov x0,0 // not balanced
100:
ldp x2,x3,[sp],16 // restaur registres
ldp x1,lr,[sp],16 // restaur registres
ret
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
/* x7 address string6 */
displayStrings: // INFO: displayStrings
stp x8,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x8,x0 // save strings number
cmp x8,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x8,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x8,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x8,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x8,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x8,#5
ble 100f
mov x0,x6
bl affichageMess
cmp x8,#6
ble 100f
mov x0,x7
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x8,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* random number */
/******************************************************************/
/* x0 contains inferior value */
/* x1 contains maxi value */
/* x0 return random number */
extRandom:
stp x1,lr,[sp,-16]! // save registers
stp x2,x8,[sp,-16]! // save registers
stp x19,x20,[sp,-16]! // save registers
sub sp,sp,16 // reserve 16 octets on stack
mov x19,x0
add x20,x1,1
mov x0,sp // store result on stack
mov x1,8 // length 8 bytes
mov x2,0
mov x8,278 // call system Linux 64 bits Urandom
svc 0
mov x0,sp // load résult on stack
ldr x0,[x0]
sub x2,x20,x19 // calculation of the range of values
udiv x1,x0,x2 // calculation range modulo
msub x0,x1,x2,x0
add x0,x0,x19 // and add inferior value
100:
add sp,sp,16 // alignement stack
ldp x19,x20,[sp],16 // restaur 2 registers
ldp x2,x8,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // retour adresse lr x30
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
 
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Expression : ((())) balanced
Expression : (()()) balanced
Expression : (())())( not balanced
Expression : ((()))))()))) not balanced
Expression : (()())())())) not balanced
Expression : ()(((()((()) not balanced
Expression : ())()(()())() not balanced
Expression : ())))((()))((( not balanced
Expression : (())()())(() not balanced
Expression : ())()))))(()( not balanced
Expression : ())()(())(()( not balanced
Expression : ())(()(()())) not balanced
Expression : ((()))()))))) not balanced
Expression : (()))((()))( not balanced
</pre>
 
Line 642 ⟶ 884:
]][][]]][]][][]][[[[[[][: not ok
]]][][][]][][[]][[[][][[: not ok
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
 
braizq="[", brader="]" // bug de Hopper :(
largo de datos=0
preparar datos (DATA_BRACKET)
obtener tamaño de datos, menos '1', guardar en 'largo de datos'
iterar
bra="", obtener dato, guardar en 'bra'
i=1, b=0, error_pos=""
iterar grupo( ++i, #( i<=len(bra) && is not neg (b) ),\
#( b += ((bra[i]==braizq) - (bra[i]==brader)) )\
#( error_pos = cat(replicate(" ",i-1),"^\n") ) )
solo si ( #(is pos(b)),\
#( error_pos=cat(cat(" ",error_pos),"(missing closed bracket)\n\n")))
solo si ( #(is neg(b)),\
#( error_pos=cat(error_pos,"(extra closed bracket)\n\n")))
 
imprimir ( #( rpad(" ",40,bra) ), ": ", \
solo si (b, "un"), "balanced\n",\
solo si (b, error_pos) )
mientras ' largo de datos-- '
terminar
 
subrutinas
 
DATA_BRACKET:
datos ("","[ [ ] [ [[] ][] ] [[]] ]","[[ ][[[ ][ ]]",\
"[][][[]]][","][[]][] [[[]]] [][]","[][] [][][[]]",\
"[ a-b * [c/d] + [[10 * sin 30 ]-1] ]",\
"[ a-b * [c/d] + [[10 * sin 30 ]]-1] ]")
back
</syntaxhighlight>
{{out}}
<pre>
: balanced
[ [ ] [ [[] ][] ] [[]] ] : balanced
[[ ][[[ ][ ]] : unbalanced
^
(missing closed bracket)
 
[][][[]]][ : unbalanced
^
(extra closed bracket)
 
][[]][] [[[]]] [][] : unbalanced
^
(extra closed bracket)
 
[][] [][][[]] : balanced
[ a-b * [c/d] + [[10 * sin 30 ]-1] ] : balanced
[ a-b * [c/d] + [[10 * sin 30 ]]-1] ] : unbalanced
^
(extra closed bracket)
</pre>
 
Line 1,202 ⟶ 1,511:
=={{header|BASIC}}==
{{works with|QBasic}}
 
<syntaxhighlight lang="qbasic">DECLARE FUNCTION checkBrackets% (brackets AS STRING)
DECLARE FUNCTION generator$ (length AS INTEGER)
Line 1,260 ⟶ 1,568:
generator$ = xx$
END FUNCTION</syntaxhighlight>
{{out}}
 
<pre> [][[][][]] OK
Sample output:
[][[][][]] OK
][[[]] NOT OK
[][] OK
Line 1,273 ⟶ 1,580:
][][[[]] NOT OK
][[]][ NOT OK
OK</pre>
 
==={{header|Applesoft BASIC}}===
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|BASIC256}}===
{{trans|Yabasic}}
<syntaxhighlight lang="basic256">s$ = "[[]][]"
print s$; " = ";
 
if not check_brackets(s$) then print "not ";
print "ok"
end
 
function check_brackets(s$)
level = 0
for i = 1 to length(s$)
c$ = mid(s$, i, 1)
begin case
case c$ = "["
level = level + 1
case c$ = "]"
level = level - 1
if level < 0 then exit for
end case
next i
return level = 0
end function</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|Commodore BASIC}}===
Line 1,299 ⟶ 1,636:
2000 DATA , [], ][, [][], ][][, [[][]], []][[]</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|BASIC256MSX Basic}}===
Based on Commodore BASIC implementation
{{trans|Yabasic}}
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="basic256">s$ = "[[]][]"
{{works with|Applesoft BASIC}}
print s$; " = ";
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS : rem 10 HOME for Applesoft BASIC
110 FOR N = 1 TO 7
120 READ S$
130 IF S$ = "" THEN PRINT"(EMPTY)";: GOTO 150
140 PRINT S$;
150 PRINT TAB(9);
160 GOSUB 190
170 NEXT N
180 END
190 S = 0
200 FOR K = 1 TO LEN(S$)
210 C$ = MID$(S$,K,1)
220 IF C$ = "[" THEN S = S+1
230 IF C$ = "]" THEN S = S-1
240 IF S < 0 THEN PRINT "NOT OK": RETURN
250 NEXT K
260 IF S = 0 THEN PRINT " OK": RETURN
270 PRINT "NOT OK"
280 RETURN
290 DATA "", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"</syntaxhighlight>
{{out}}
<pre>(EMPTY) OK
[] OK
][ NOT OK
[][] OK
][][ NOT OK
[[][]] OK
[]][[] NOT OK</pre>
 
==={{header|True BASIC}}===
if not check_brackets(s$) then print "not ";
{{trans|Run BASIC}}
print "ok"
<syntaxhighlight lang="qbasic">DIM brk$(10)
end
LET brk$(1) = "[[[][]]]"
LET brk$(2) = "[[[]][[[][[][]]]]]"
LET brk$(3) = "][][]][["
LET brk$(4) = "[][][]"
LET brk$(5) = "[][]][]][[]]][[["
LET brk$(6) = "]][[[[]]]][]]][[[["
LET brk$(7) = "[[][[[]]][]]"
LET brk$(8) = "[]][][][[[]]"
LET brk$(9) = "][]][["
LET brk$(10) = "[]][][][[]"
 
FOR i = 1 TO 7
function check_brackets(s$)
level LET b$ = 0brk$(i)
for i =DO 1WHILE to lengthPOS(sb$,"[]") <> 0
c$ LET x = midPOS(sb$, i, 1"[]")
IF x > 0 THEN LET b$ = (b$)[1:x-1] & (b$)[x+2:maxnum]
begin case
case c$ = "["LOOP
IF levelTRIM$(b$) = level +"" 1THEN
case c$ =PRINT "] OK ";
ELSE
level = level - 1
PRINT if"Not levelOK < 0 then exit for";
endEND caseIF
PRINT brk$(i)
next i
NEXT i
return level = 0
end functionEND</syntaxhighlight>
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="qbasic">@(0) := "[]][][][[]"
@(1) := "[[[][]]]"
@(2) := "[[[]][[[][[][]]]]]"
@(3) := "][][]][["
@(4) := "[][][]"
@(5) := "[][]][]][[]]][[["
@(6) := "]][[[[]]]][]]][[[["
@(7) := "[[][[[]]][]]"
@(8) := "[]][][][[[]]"
@(9) := "][]][["
 
For x = 0 To 9
Print Using "(_#)";x,Show (@(x));Tab (30);
Do While (Set (a, Find(@(x), "[]")) < 0) = 0
@(x) = Join (Clip (@(x), Len (@(x)) - a), Chop (@(x), a + 2))
Loop
Print "is";Show (Iif (Len (@(x))," not "," "));"balanced"
Next</syntaxhighlight>
{{Out}}
<pre>( 0) []][][][[] is not balanced
( 1) [[[][]]] is balanced
( 2) [[[]][[[][[][]]]]] is balanced
( 3) ][][]][[ is not balanced
( 4) [][][] is balanced
( 5) [][]][]][[]]][[[ is not balanced
( 6) ]][[[[]]]][]]][[[[ is not balanced
( 7) [[][[[]]][]] is balanced
( 8) []][][][[[]] is not balanced
( 9) ][]][[ is not balanced
 
0 OK, 0:472 </pre>
 
=={{header|Batch File}}==
Line 2,354 ⟶ 2,771:
false
false</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func balanced code$ .
for i to len code$
h$ = substr code$ i 1
if h$ = "["
br += 1
elif h$ = "]"
br -= 1
.
if br < 0
return 0
.
.
return if br = 0
.
repeat
inp$ = input
until inp$ = "eof"
print inp$ & "\t" & balanced inp$
.
#
input_data
 
[]
[][]
[[][]]
][
][][
[]][[]
eof
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 2,386 ⟶ 2,836:
</syntaxhighlight>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BalancedBrackets {
Boolean balanced(String text) {
Int depth = 0;
for (Char ch : text) {
switch (ch, depth) {
case ('[', _):
++depth;
break;
case (']', 0):
return False;
case (']', _):
--depth;
break;
}
}
return depth==0;
}
 
@Inject Console console;
void run() {
String[] tests =
[
"[]",
"[][]",
"[]][[]",
"[[[]][]]",
"][[[[]][]]",
"[[[]][[]][]]",
"]][[]][[[[][]]",
"[[]]]][]][[][[[]",
];
Int longest = tests.map(s -> s.size).reduce(0, (max, len) -> max.maxOf(len));
for (String test : tests) {
console.print($"{test}{' ' * (longest-test.size)} {balanced(test) ? "OK" : "NOT OK"}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
[] OK
[][] OK
[]][[] NOT OK
[[[]][]] OK
][[[[]][]] NOT OK
[[[]][[]][]] OK
]][[]][[[[][]] NOT OK
[[]]]][]][[][[[] NOT OK
</pre>
 
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">import// system'routines;Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order.
// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order),
// none of which mis-nest.
 
import system'routines;
import extensions;
import extensions'text;
Line 2,395 ⟶ 2,902:
randomBrackets(len)
{
if (0 == len)
{
^emptyString
}
else
{
var brackets :=
Array.allocate(len).populate::(i => $91)
+
Array.allocate(len).populate::(i => $93);
 
brackets := brackets.randomize(len * 2);
 
^ brackets.summarize(new StringWriter()).toString()
}
}
 
extension op
{
get isBalanced()
{
var counter := new Integer(0);
self.seekEach::(ch => counter.append((ch==$91).iif(1,-1)) < 0);
^ (0 == counter)
}
}
 
public program()
{
for(int len := 0,; len < 9,; len += 1)
{
var str := randomBrackets(len);
 
console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced")
};
 
console.readChar()
}</syntaxhighlight>
{{out}}
Line 2,949 ⟶ 3,456:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators formatting kernel math random sequences strings ;
This code implements the second part of the task: it reads from standard input an arbitrary string of opening and closing brackets, and checks whether it's balanced or not.
IN: rosetta-code.balanced-brackets
 
: balanced? ( str -- ? )
0 swap [
{
{ CHAR: [ [ 1 + t ] }
{ CHAR: ] [ 1 - dup 0 >= ] }
[ drop t ]
} case
] all? swap zero? and ;
 
: bracket-pairs ( n -- str )
[ "[]" ] replicate "" concat-as ;
 
: balanced-brackets-main ( -- )
5 bracket-pairs randomize dup balanced? "" "not " ?
"String \"%s\" is %sbalanced.\n" printf ;
 
MAIN: balanced-brackets-main</syntaxhighlight>
 
The code below implements only the second part of the task: it reads from standard input an arbitrary string of opening and closing brackets, and checks whether it's balanced or not. Unlike the solution above, this one uses local variables.
<syntaxhighlight lang="factor">USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
Line 2,972 ⟶ 3,500:
readln
balanced</syntaxhighlight>
 
Some more idiomatic solution might be as follows:
 
<syntaxhighlight lang="factor">USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
 
: map-braces ( -- qout )
[
{
{ "[" [ drop 1 ] }
{ "]" [ drop -1 ] }
[ drop 0 ]
} case
]
;
 
: balanced? ( str -- ? )
map-braces map sum 0 =
;
 
"[1+2*[3+4*[5+6]-3]*4-[3*[3+3]]]" balanced?
-- Data stack:
t
</syntaxhighlight>
 
=={{header|Fantom}}==
Line 3,276 ⟶ 3,780:
include "NSLog.incl"
 
local fn BracketBalance( strWithBracketsstrWithBracket as CFStringRef ) as CFStringRef
NSInteger i, bracketTracker = 0
CFStringRef result
Line 3,282 ⟶ 3,786:
CFCharacterSetRef bracketSet = fn CharacterSetWithCharactersInString( @"[]" )
CFCharacterSetRef bracketsOnlySet = fn CharacterSetInvertedSet( bracketSet )
CFStringRefCFArrayRef trimmedStr trimmedSArray = fn StringByTrimmingCharactersInSetStringComponentsSeparatedByCharactersInSet( strWithBracketsstrWithBracket, bracketsOnlySet )
CFStringRef trimmedStr = fn ArrayComponentsJoinedByString( trimmedSArray, @"" )
NSUInteger strLen = len( trimmedStr )
Line 3,469 ⟶ 3,974:
Balanced("[[[]][]]]");
# false</syntaxhighlight>
 
=={{header|GDScript}}==
{{works with|Godot|4.0}}
 
<syntaxhighlight lang="gdscript">
extends MainLoop
 
func generate_brackets(n: int) -> String:
var brackets: Array[String] = []
 
# Add opening and closing brackets
brackets.resize(2*n)
for i in range(0, 2*n, 2):
brackets[i] = "["
brackets[i+1] = "]"
 
brackets.shuffle()
return "".join(brackets)
 
func is_balanced(str: String) -> bool:
var unclosed_brackets := 0
for c in str:
match c:
"[":
unclosed_brackets += 1
"]":
if unclosed_brackets == 0:
return false
unclosed_brackets -= 1
_:
return false
return unclosed_brackets == 0
 
func _process(_delta: float) -> bool:
randomize()
 
for i in range(6):
var bracket_string := generate_brackets(i)
 
if is_balanced(bracket_string):
print("%sOK" % bracket_string.rpad(13))
else:
print("%sNOT OK" % bracket_string.rpad(11))
 
return true # Exit
</syntaxhighlight>
 
=={{header|Go}}==
Line 3,900 ⟶ 4,451:
 
-------------------- BALANCED BRACKETS -------------------
 
nesting :: String -> [Int]
nesting = tail . scanl (flip level) 0
where
level '[' = succ
level ']' = pred
level _ = id
 
bracketProblemIndex :: String -> Maybe Int
Line 3,910 ⟶ 4,469:
| otherwise = Nothing
 
nesting :: String -> [Int]
nesting = tail . scanl level 0
where
level n '[' = succ n
level n ']' = pred n
level n _ = n
 
--------------------------- TEST -------------------------
Line 4,413 ⟶ 4,966:
']]][[][][][]' problem
^</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq.'''
 
In this entry, two solutions are given: the first uses
an external source of entropy and jq's `until` control structure;
the second uses a low-entropy PRNG based on jq's `now`,
and `gsub/2.`
===High entropy solution using `until`===
<syntaxhighlight lang=bash>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr '
 
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def prb: 2 | prn == 0;
 
def balanced:
{array: explode, parity: 0}
| until( .result | type == "boolean";
if .array == [] then .result = (.parity == 0)
else .parity += (.array[0] | if . == 91 then 1 else -1 end)
| if .parity < 0 then .result = false
else .array |= .[1:]
end
end ).result ;
 
def task($n):
if $n%2 == 1 then null
else [ (range(0; $n) | if prb then "[" else "]" end) // ""]
| add
| "\(.): \(balanced)"
end;
 
task(0),
task(2),
(range(0;10) | task(4))
</syntaxhighlight>
{{output}}
<pre>
: true
[[: false
[][[: false
][[[: false
]][[: false
[[]]: true
]][[: false
][[[: false
[[[[: false
[][[: false
][[[: false
[]][: false
</pre>
===Low entropy solution with `gsub`===
<syntaxhighlight lang=jq>
def prb: (now|tostring[-1:] | tonumber) % 2 == 0;
 
def balanced:
if length==0 then true
elif .[:1] == "]" then false
else test("[[][]]") and (gsub("[[][]]"; "") | balanced)
end;
 
def task($n):
if $n%2 == 1 then null
else
(reduce range(0; $n) as $i ("";
. + (if prb then "[" else "]" end) ))
| "\(.): \(balanced)"
end;
 
task(0),
task(2),
(range(0;10) | task(4))
</syntaxhighlight>
{{output}}
Similar to above.
 
=={{header|Julia}}==
Line 4,701 ⟶ 5,338:
print(isBalanced(RS))
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
module Balanced_brackets{
// Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
function randomBrackets(max as long) {
if max<1 then max=1
def putbracket()=mid$("[[[[]]",random(1,6),1)
dim a(random(1, max)) as string<<putbracket()
=a()#str$("")
}
// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
function check(s as string) {
long i, level
for i=1 to len(s)
if mid$(s,i,1)="[" then level++ else level--
if level<0 then exit for
next
=level=0
}
string k
boolean m
do
k=randomBrackets(10)
m=check(k)
print k;@(12);": ";if$(m->"OK", "NOT OK")
until m
}
Balanced_brackets
</syntaxhighlight>
{{out}}
<pre>
[[[] : NOT OK
[[][]] : OK
</pre>
 
=={{header|Maple}}==
Line 5,051 ⟶ 5,724:
'][[][]]]][[[[][]' is not balanced
'][][][][][[][[]]][' is not balanced</pre>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
def gen_brackets [n: int] { 1..$in | each {["[" "]"]} | flatten | shuffle | str join }
 
def check_brackets [] {
split chars | reduce --fold 0 {|x, d|
if ($d < 0) {-1} else {
$d + (if ($x == "[") {1} else {-1})
}
} | $in > -1
}
 
 
1..10 | each {gen_brackets $in | {brackets: $in, valid: ($in | check_brackets)}} | print
</syntaxhighlight>
{{out}}
<pre>
╭───┬──────────────────────┬───────╮
│ # │ brackets │ valid │
├───┼──────────────────────┼───────┤
│ 0 │ ][ │ false │
│ 1 │ []][ │ false │
│ 2 │ [[][]] │ true │
│ 3 │ [[[][]]] │ true │
│ 4 │ ]]][[[[][] │ false │
│ 5 │ [][][][[[]]] │ true │
│ 6 │ ]]]]][]][[[[[[ │ false │
│ 7 │ ][[][]]]][[][[[] │ false │
│ 8 │ []]]][][][[][]][[[ │ false │
│ 9 │ ][][][[[[[]]]][[]][] │ false │
╰───┴──────────────────────┴───────╯
</pre>
 
=={{header|Oberon-2}}==
Line 5,433 ⟶ 6,139:
}</syntaxhighlight>
 
<code>Regexp::Common::balanced</code> can give such a regexp too (non-brackethere charsvia allowed).a subroutine Its recent versions use the subpattern recursion and are hence also only for Perl 5.10 and up.call)
 
<syntaxhighlight lang="perl">use Regexp::Common 'balancedRE_balanced';
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/;
sub balanced {
return shift =~ $re;RE_balanced(-parens=>'[]')
}
}</syntaxhighlight>
</syntaxhighlight>
 
Alternative implementation, using straightforward depth counting:
Line 6,564 ⟶ 7,270:
bracket string [[]] is ok.
bracket string ]]]][]]]]]]]]] is not ok.
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
1 OVER SIZE
'''WHILE''' DUP2 * 0 > '''REPEAT'''
3 PICK OVER DUP SUB
'''IF''' "[]" SWAP POS '''THEN'''
LAST 2 * 3 - ROT + SWAP '''END'''
1 -
'''END''' DROP
1 SAME "" "Not " '''IFTE''' "OK" +
≫ ''''BALBKT'''' STO
≪ { "" "[]" "[][]" "[[][]]" "][" "][][" "[]][[]" } → ts
1 ts SIZE '''FOR''' j
ts j GET '''BALBKT''' " → " SWAP + + '''NEXT'''
≫ ≫ ''''TASK'''' STO
{{out}}
<pre>
" → OK"
"[] → OK"
"[][] → OK"
"[[][]] → OK"
"][ → Not OK"
"][][ → Not OK"
"[]][[] → Not OK"
</pre>
 
Line 7,340 ⟶ 8,075:
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program balanced_brackets;
setrandom(0);
 
loop for length in [1..10] do
s := generate length;
print(balanced s, s);
end loop;
 
op generate(n);
s := "["*n + "]"*n;
loop for i in [n*2, n*2-1..2] do
j := 1 + random(i - 1);
[s(i), s(j)] := [s(j), s(i)];
end loop;
return s;
end op;
 
op balanced(s);
depth := 0;
loop for c in s do
case c of
("["):
depth +:= 1;
("]"):
depth -:= 1;
if depth<0 then return false; end if;
end case;
end loop;
return depth = 0;
end op;
end program;</syntaxhighlight>
{{out}}
<pre>#F ][
#F ]][[
#T [[]][]
#F [[]]][][
#F ][[][][]][
#F ]][]]]][[[[[
#F ]]][[]]][[[[[]
#T [[][][[][[]][]]]
#F []][[]]]][][][[][[
#F []][]]][]][][[[][[][</pre>
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func balanced (str) {
Line 8,224 ⟶ 9,002:
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import datatypes as dt
 
fn is_valid(bracket string) bool {
Line 8,264 ⟶ 9,042:
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="ecmascriptwren">import "random" for Random
 
var isBalanced = Fn.new { |s|
Anonymous user