Balanced brackets: Difference between revisions

Added uBasic/4tH version
(Added solution for Action!)
imported>Thebeez
(Added uBasic/4tH version)
 
(48 intermediate revisions by 25 users not shown)
Line 19:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F gen(n)
V txt = [‘[’, ‘]’] * n
random:shuffle(&txt)
Line 37:
L(n) 0..9
V s = gen(n)
print(s‘’(‘ ’ * (20 - s.len))‘is ’(I is_balanced(s) {‘balanced’} E ‘not balanced’))</langsyntaxhighlight>
{{out}}
<pre>
Line 53:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Balanced brackets 28/04/2016
BALANCE CSECT
USING BALANCE,R13 base register and savearea pointer
Line 153:
XDEC DS CL12
REGS
END BALANCE</langsyntaxhighlight>
{{out}}
<pre>
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>
 
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
CLASS lcl_balanced_brackets DEFINITION.
PUBLIC SECTION.
Line 276 ⟶ 518:
cl_demo_output=>display( ).
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 303 ⟶ 545:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Generate(BYTE size CHAR ARRAY s)
BYTE i,half
 
Line 374 ⟶ 616:
PrintE("balanced")
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Balanced_brackets.png Screenshot from Atari 8-bit computer]
Line 395 ⟶ 637:
Using #HASH-OFF
</pre>
<syntaxhighlight lang="acurity architect">
<lang Acurity Architect>
FUNCTION bBRACKETS_MATCH(zStringWithBrackets: STRING): STRING
VAR sCount: SHORT
Line 415 ⟶ 657:
RETURN zOK
ENDFUNCTION
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 426 ⟶ 668:
=={{header|Ada}}==
brackets.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Strings.Fixed;
Line 482 ⟶ 724:
end loop;
end loop;
end Brackets;</langsyntaxhighlight>
 
Output:
Line 503 ⟶ 745:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">unbalanced(data s)
{
integer b, i;
Line 537 ⟶ 779:
 
0;
}</langsyntaxhighlight>
Sample output:
<pre> is balanced
Line 552 ⟶ 794:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># generates a string of random opening and closing brackets. The number of #
# each type of brackets is speccified in length #
PROC get brackets = ( INT length ) STRING:
Line 614 ⟶ 856:
test check brackets( get brackets( length ) )
OD
OD</langsyntaxhighlight>
{{out}}
<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 649 ⟶ 958:
<br clear=both>
==={{header|Java}}===
<syntaxhighlight lang="text">
grammar balancedBrackets ;
 
Line 669 ⟶ 978:
NEWLINE : '\r'? '\n'
;
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 694 ⟶ 1,003:
and a function to check whether a given string of brackets is balanced.
 
<langsyntaxhighlight APLlang="apl">gen ← (⊂+?+)⍨ ⌷ ('[]'/⍨⊢)
bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢)</langsyntaxhighlight>
 
Sample run for 0..N..10:
 
<langsyntaxhighlight APLlang="apl"> ↑{br←gen ⍵ ⋄ br,': ',(1+bal br)⊃'Bad' 'Good'}¨0,⍳10
: Good
[]: Good
Line 710 ⟶ 1,019:
[[][[]]][[[[]]]]: Good
[[[]][[[[][]][]]]]: Good
]][][][][[][][]][[[]: Bad</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 717 ⟶ 1,026:
(ES6 functionally composed version)
 
<langsyntaxhighlight AppleScriptlang="applescript">-- CHECK NESTING OF SQUARE BRACKET SEQUENCES ---------------------------------
 
-- Zero-based index of the first problem (-1 if none found):
Line 899 ⟶ 1,208:
end script
end if
end mReturn</langsyntaxhighlight>
'''Sample output:'''
<pre>'][' problem
Line 914 ⟶ 1,223:
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="arm_assembly">
<lang ARM_Assembly>
.data
 
Line 974 ⟶ 1,283:
mov pc, lr
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">isBalanced: function [s][
cnt: 0
Line 1,000 ⟶ 1,309:
if? isBalanced str -> print " OK"
else -> print " Not OK"
]</langsyntaxhighlight>
 
{{out}}
Line 1,016 ⟶ 1,325:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Generate 10 strings with equal left and right brackets
Loop, 5
{
Line 1,047 ⟶ 1,356:
}
Return "OK"
}</langsyntaxhighlight>
Output:
<pre>
Line 1,063 ⟶ 1,372:
 
A second example repeatedly replacing []:
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 5
{
B = %A_Index%
Line 1,085 ⟶ 1,394:
StringReplace, Str, Str,[],,All
Return Str ? "False" : "True"
}</langsyntaxhighlight>
Sample output:
<pre>
Line 1,101 ⟶ 1,410:
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
#include <Array.au3>
Local $Array[1]
Line 1,130 ⟶ 1,439:
Return 1
EndFunc
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
print isbb("[]")
Line 1,155 ⟶ 1,464:
return (s==0)
}
</syntaxhighlight>
</lang>
Output:
<pre>1
Line 1,165 ⟶ 1,474:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">FOR len = 0 TO 18 STEP 2
 
str$ = ""
Line 1,187 ⟶ 1,496:
PRINT "BAD: ", str$
ENDIF
NEXT</langsyntaxhighlight>
{{out}}
<pre>OK:
Line 1,202 ⟶ 1,511:
=={{header|BASIC}}==
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">DECLARE FUNCTION checkBrackets% (brackets AS STRING)
 
<lang qbasic>DECLARE FUNCTION checkBrackets% (brackets AS STRING)
DECLARE FUNCTION generator$ (length AS INTEGER)
 
Line 1,259 ⟶ 1,567:
NEXT
generator$ = xx$
END FUNCTION</langsyntaxhighlight>
{{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}}===
Based on ZX Spectrum BASIC implementation
<langsyntaxhighlight lang="basic">10 PRINT CHR$(147): REM CLEAR SCREEN
20 FOR N=1 TO 7
30 READ S$
Line 1,297 ⟶ 1,634:
1090 PRINT "NOT OK"
1100 RETURN
2000 DATA , [], ][, [][], ][][, [[][]], []][[]</langsyntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|MSX Basic}}===
Based on Commodore BASIC implementation
{{works with|MSX BASIC|any}}
{{works with|Applesoft BASIC}}
{{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}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="qbasic">DIM brk$(10)
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
LET b$ = brk$(i)
DO WHILE POS(b$,"[]") <> 0
LET x = POS(b$,"[]")
IF x > 0 THEN LET b$ = (b$)[1:x-1] & (b$)[x+2:maxnum]
LOOP
IF TRIM$(b$) = "" THEN
PRINT " OK ";
ELSE
PRINT "Not OK ";
END IF
PRINT brk$(i)
NEXT i
END</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}}==
Uses the rewrite rule <code>"[]" -> null</code> to check if brackets are balanced.
<langsyntaxhighlight lang="dos">:: Balanced Brackets Task from Rosetta Code
:: Batch File Implementation
Line 1,353 ⟶ 1,796:
set "old=%new%"
set "new=%old:[]=%"
goto check_loop</langsyntaxhighlight>
{{out}}
<pre>[][][[[[]]][]]]][[][ is NOT Balanced.
Line 1,378 ⟶ 1,821:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">FOR x%=1 TO 10
test$=FNgenerate(RND(10))
PRINT "Bracket string ";test$;" is ";FNvalid(test$)
Line 1,406 ⟶ 1,849:
IF count%<0 THEN ="not OK."
NEXT x%
="OK."</langsyntaxhighlight>
<pre>Bracket string [[[][]]] is OK.
Bracket string [[[]][[[][[][]]]]] is OK.
Line 1,421 ⟶ 1,864:
{{works with|befungee}}
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.
<langsyntaxhighlight Befungelang="befunge">v > "KO TON" ,,,,,, v
> ~ : 25*- #v_ $ | > 25*, @
> "KO" ,, ^
Line 1,427 ⟶ 1,870:
> \ : 1991+*+- #v_v
\ $
^ < <$<</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 1,436 ⟶ 1,879:
This allows for a particular simple implementation:
 
<langsyntaxhighlight lang="bqn">Gen ← (•rand.Deal⊏⥊⟜"[]") 2⊸×
Bal ← {
Mul ← {a‿b𝕊x‿y: ⟨a+0⌈x-b, y+0⌈b-x⟩}
0‿0 ≡ 0‿0("]["⊸=⊸Mul)´𝕩
}</langsyntaxhighlight>
 
{{out}}
Line 1,454 ⟶ 1,897:
=={{header|Bracmat}}==
Bracmat has no 'random' function, so the shuffle is a bit improvised. A variable <code>someNumber</code> is initialised with a big number is repeatedly divided by the number of '['s in the test string until zero. The remainders are used as index to partition and swap the first half of the test string. Then the second half and first half are also swapped. The test whether the test string is balanced is simple, but not very efficient.
<langsyntaxhighlight lang="bracmat">( (bal=|"[" !bal "]" !bal)
& ( generate
= a j m n z N S someNumber
Line 1,480 ⟶ 1,923:
& !L+1:<11:?L
)
);</langsyntaxhighlight>
Output:
<pre>:Balanced
Line 1,495 ⟶ 1,938:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">string.prototype.balanced? = {
brackets = []
balanced = true
Line 1,525 ⟶ 1,968:
{ p "#{test} is balanced" }
{ p "#{test} is not balanced" }
}</langsyntaxhighlight>
 
Output:
Line 1,540 ⟶ 1,983:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
Line 1,582 ⟶ 2,025:
while(n<9) doSeq(n++);
return 0;
}</langsyntaxhighlight>result:<syntaxhighlight lang="text">'': True
'[]': True
']][[': False
Line 1,590 ⟶ 2,033:
']]]][[[]][[[': False
']]]]]][][[[[[[': False
'[][]][[][[[]]][]': False</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,634 ⟶ 2,077:
}
}
}</langsyntaxhighlight>
Sample output:
<pre>"" is balanced.
Line 1,645 ⟶ 2,088:
"[]]][][]][[][[" is not balanced.
"[]]][]]][[][[][[" is not balanced.</pre>
<langsyntaxhighlight lang="csharp">
// simple solution
string input = Console.ReadLine();
Line 1,670 ⟶ 2,113:
Console.WriteLine("Not Okay");
 
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <string>
Line 1,705 ⟶ 2,148:
std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n";
}
}</langsyntaxhighlight>
Output:
<pre> ok:
Line 1,719 ⟶ 2,162:
 
=={{header|Ceylon}}==
<langsyntaxhighlight Ceylonlang="ceylon">import com.vasileff.ceylon.random.api {
platformRandom,
Random
Line 1,745 ⟶ 2,188:
ints.filter((i) => i != 0)
.scan(0)(plus<Integer>)
.every((i) => i >= 0);</langsyntaxhighlight>
 
Output:
Line 1,762 ⟶ 2,205:
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn gen-brackets [n]
(->> (concat (repeat n \[) (repeat n \]))
shuffle
Line 1,775 ⟶ 2,218:
(when (= (peek stack) \[)
(recur coll (pop stack))))
(zero? (count stack)))))</langsyntaxhighlight>
 
There are other ways to express the <code>balanced?</code> function.
 
* We can use <code>reduce</code> to consume the sequence:
:<langsyntaxhighlight Clojurelang="clojure">(defn balanced? [s]
(empty?
(reduce
Line 1,790 ⟶ 2,233:
(reduced [:UNDERFLOW]))))
'()
s)))</langsyntaxhighlight>
 
* Only <code>[</code>s are put on the stack. We can just count the unmatched ones.
:<langsyntaxhighlight Clojurelang="clojure">(defn balanced? [s]
(let [opens-closes (->> s
(map {\[ 1, \] -1})
(reductions + 0))]
(and (not-any? neg? opens-closes) (zero? (last opens-closes))))) </langsyntaxhighlight>
 
Output:
Line 1,815 ⟶ 2,258:
["][][[]]][[][][][" nil]
["][][]]][]][[[][[[]" nil]</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs the random number generator from
% "misc.lib" that comes with PCLU.
 
shuffle = proc [T: type] (a: array[t])
aT = array[t]
for i: int in int$from_to_by(aT$size(a)-1,0,-1) do
x: int := aT$low(a) + i
y: int := aT$low(a) + random$next(i+1)
temp: T := a[x]
a[x] := a[y]
a[y] := temp
end
end shuffle
 
brackets = proc (n: int) returns (string)
br: array[char] := array[char]$[]
for i: int in int$from_to(1,2*n) do
if i<=n then array[char]$addh(br, '[')
else array[char]$addh(br, ']')
end
end
shuffle[char](br)
return(string$ac2s(br))
end brackets
 
balanced = proc (br: string) returns (bool)
depth: int := 0
for c: char in string$chars(br) do
if c='[' then depth := depth + 1
elseif c=']' then depth := depth - 1
end
if depth<0 then return(false) end
end
return(depth = 0)
end balanced
 
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
for size: int in int$from_to(0, 10) do
b: string := brackets(size)
stream$puts(po, "\"" || b || "\": ")
if balanced(b) then
stream$putl(po, "balanced")
else
stream$putl(po, "not balanced")
end
end
end start_up</syntaxhighlight>
{{out}}
<pre>"": balanced
"[]": balanced
"[][]": balanced
"[[]][]": balanced
"[[]][[]]": balanced
"][[]][][[]": not balanced
"[][][]][]][[": not balanced
"][]][]]][][[[[": not balanced
"[][[]][][][[[]]]": balanced
"][[][][]][[]][][[]": not balanced
"]]]][[[[]][][][[][[]": not balanced</pre>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. test-balanced-brackets.
 
Line 1,915 ⟶ 2,423:
.
 
END PROGRAM check-if-balanced.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
isBalanced = (brackets) ->
openCount = 0
Line 1,934 ⟶ 2,442:
for brackets in bracketsCombinations 4
console.log brackets, isBalanced brackets
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> coffee balanced.coffee
[[[[ false
Line 1,954 ⟶ 2,462:
]]][ false
]]]] false
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun string-of-brackets (n)
(let* ((len (* 2 n))
Line 1,985 ⟶ 2,493:
(let ((s (string-of-brackets i)))
(format t "~3A: ~A~%" (balancedp s) s))))
</syntaxhighlight>
</lang>
 
Output:
Line 2,005 ⟶ 2,513:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Brackets;
IMPORT StdLog, Args, Stacks (* See Task Stacks *);
Line 2,066 ⟶ 2,574:
 
END Brackets.
</syntaxhighlight>
</lang>
Execute: ^Q Brackets.Do [] [][] [[][]] ][ ][][ []][[]~<br/>
Output:
Line 2,079 ⟶ 2,587:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">def generate(n : Int)
(['[',']'] * n).shuffle.join # Implicit return
end
Line 2,104 ⟶ 2,612:
str = generate(i)
puts "#{str}: #{is_balanced(str)}"
end</langsyntaxhighlight>
 
Output:
Line 2,122 ⟶ 2,630:
===Standard Version===
D standard library has a [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html#balancedParens function] for this.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.random, std.range;
 
void main() {
Line 2,129 ⟶ 2,637:
writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s);
}
}</langsyntaxhighlight>
{{out}}
<pre> OK: []
Line 2,142 ⟶ 2,650:
===Imperative Version===
{{trans|Raku}}
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.range, std.algorithm;
 
bool isBalanced(in string txt) pure nothrow {
Line 2,164 ⟶ 2,672:
writeln(s.isBalanced ? " OK " : "Bad ", s);
}
}</langsyntaxhighlight>
The output is similar.
 
===Functional Style===
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.range, std.algorithm;
 
bool isBalanced(in string s, in char[2] pars="[]") pure nothrow @safe @nogc {
Line 2,187 ⟶ 2,695:
writeln(s.isBalanced ? " OK " : "Bad ", s);
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">procedure Balanced_Brackets;
 
var BracketsStr : string;
Line 2,221 ⟶ 2,729:
writeln(BracketsStr+': not OK');
end;
end;</langsyntaxhighlight>
 
<pre>
Line 2,236 ⟶ 2,744:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">matching?:
swap 0
for c in chars:
Line 2,254 ⟶ 2,762:
!. matching? "]["
!. matching? "][]["
!. matching? "[]][[]"</langsyntaxhighlight>
{{out}}
<pre>true
Line 2,263 ⟶ 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}}==
<langsyntaxhighlight lang="scheme">
(define (balance str)
(for/fold (closed 0) ((par str))
Line 2,294 ⟶ 2,835:
❌ "[[][]]]["
</syntaxhighlight>
</lang>
 
=={{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">// Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order.
<lang elena>import system'routines;
// 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,304 ⟶ 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()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,361 ⟶ 2,959:
{{trans|Erlang}}
{{works with|Elixir|1.1}}
<langsyntaxhighlight lang="elixir">defmodule Balanced_brackets do
def task do
Enum.each(0..5, fn n ->
Line 2,387 ⟶ 2,985:
end
 
Balanced_brackets.task</langsyntaxhighlight>
 
{{out}}
Line 2,400 ⟶ 2,998:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( balanced_brackets ).
-export( [generate/1, is_balanced/1, task/0] ).
Line 2,430 ⟶ 3,028:
task_balanced( true ) -> "OK";
task_balanced( false ) -> "NOT OK".
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,443 ⟶ 3,041:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function check_brackets(sequence s)
integer level
level = 0
Line 2,487 ⟶ 3,085:
puts(1," NOT OK\n")
end if
end for</langsyntaxhighlight>
 
Sample output:
Line 2,509 ⟶ 3,107:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">bracketReport
=LAMBDA(bracketPair,
LAMBDA(s,
Line 2,594 ⟶ 3,192:
)
)
)</langsyntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<langsyntaxhighlight lang="lisp">APPENDCOLS
=LAMBDA(xs,
LAMBDA(ys,
Line 2,707 ⟶ 3,305:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 2,822 ⟶ 3,420:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let isBalanced str =
let rec loop count = function
| ']'::_ when count = 0 -> false
Line 2,843 ⟶ 3,441:
for n in 1..10 do
let s = generate n
printfn "\"%s\" is balanced: %b" s (isBalanced s)</langsyntaxhighlight>
 
Output:
Line 2,858 ⟶ 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
<lang Factor>USING: io formatting locals kernel math sequences unicode.case ;
 
: 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,880 ⟶ 3,499:
 
readln
balanced</langsyntaxhighlight>
 
Some more idiomatic solution might be as follows:
 
<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
</lang>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 2,948 ⟶ 3,543:
}
}
</syntaxhighlight>
</lang>
 
Output (for n=3):
Line 2,976 ⟶ 3,571:
=={{header|Forth}}==
{{works with|4tH|3.61.1}}
<langsyntaxhighlight lang="forth">include lib/choose.4th ( n1 -- n2)
include lib/ctos.4th ( n -- a 1)
 
Line 2,998 ⟶ 3,593:
; \ evaluate string and print result
 
make[] eval[]</langsyntaxhighlight>
'''Examples''':<pre>[][[]] OK
[[[[]][[ NOT OK
Line 3,014 ⟶ 3,609:
=={{header|Fortran}}==
Please see the compilation and program execution result as comments at the top of this source:
<langsyntaxhighlight lang="fortran">
! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe
! $ ./f
Line 3,112 ⟶ 3,707:
end subroutine generate
end program balanced_brackets
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isBalanced(s As String) As Boolean
Line 3,159 ⟶ 3,754:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
Sample output (last 7 lines random) :
{{out}}
Line 3,177 ⟶ 3,772:
][[[]][] NOT OK
[][[[[][ NOT OK
</pre>
 
 
=={{header|FutureBasic}}==
Filters out non-bracket characters prior to evaluation.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn BracketBalance( strWithBracket as CFStringRef ) as CFStringRef
NSInteger i, bracketTracker = 0
CFStringRef result
CFCharacterSetRef bracketSet = fn CharacterSetWithCharactersInString( @"[]" )
CFCharacterSetRef bracketsOnlySet = fn CharacterSetInvertedSet( bracketSet )
CFArrayRef trimmedSArray = fn StringComponentsSeparatedByCharactersInSet( strWithBracket, bracketsOnlySet )
CFStringRef trimmedStr = fn ArrayComponentsJoinedByString( trimmedSArray, @"" )
NSUInteger strLen = len( trimmedStr )
// Empty string, no brackets
if ( strLen == 0 ) then result = @"No brackets" : exit fn
// String with odd number of brackets is unbalanced
if ( strLen mod 2 ) then result = @"Unbalanced" : exit fn
for i = 0 to strLen - 1
CFStringRef bracket = fn StringWithFormat( @"%C", fn StringCharacterAtIndex( trimmedStr, i ) )
if fn StringisEqual( bracket, @"[" ) then bracketTracker++
if fn StringisEqual( bracket, @"]" ) then bracketTracker--
if bracketTracker < 0 then result = @"Unbalanced" : break
next
if bracketTracker == 0 then result = @"Balanced"
end fn = result
 
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"" ) ), @"" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[" ) ), @"[" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"]" ) ), @"]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[]" ) ), @"[]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[[]" ) ), @"[[]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[]]" ) ), @"[]]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[][]" ) ), @"[][]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"][" ) ), @"][" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"][][" ) ), @"][][" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[[]][][][[][]]" ) ), @"[[]][][][[][]]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"][[]][][][]]][[" ) ), @"][[]][][][]]][[" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[[[abc]][[d]]]]]" ) ), @"[[[abc]][[def]]]]]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[[[abc]]][[[[[d]]]]]" ) ), @"[[[abc]]][[[[[def]]]]]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"[][abc]]][[[[[d]]]]]" ) ), @"[][abc]]][[[[[def]]]]]" )
NSLog( @"%12s: %@", fn StringUTF8String( fn BracketBalance( @"The quick brown fox" ) ), @"The quick brown fox" )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
No brackets:
Unbalanced: [
Unbalanced: ]
Balanced: []
Unbalanced: [[]
Unbalanced: []]
Balanced: [][]
Unbalanced: ][
Unbalanced: ][][
Balanced: [[]][][][[][]]
Unbalanced: ][[]][][][]]][[
Unbalanced: [[[abc]][[def]]]]]
Balanced: [[[abc]]][[[[[def]]]]]
Unbalanced: [][abc]]][[[[[def]]]]]
No brackets: The quick brown fox
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=8960fb267af43f0549d2cfe04288a2d4 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work
 
siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line
Line 3,253 ⟶ 3,916:
Return sBrk 'Return the sBrk array
 
End</langsyntaxhighlight>
Output:
<pre>
Line 3,275 ⟶ 3,938:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Balanced := function(L)
local c, r;
r := 0;
Line 3,310 ⟶ 3,973:
 
Balanced("[[[]][]]]");
# false</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,366 ⟶ 4,075:
}
testBalanced("()")
}</langsyntaxhighlight>
Output:
<pre>
Line 3,384 ⟶ 4,093:
=={{header|Groovy}}==
Generate Arbitrary String of Bracket Pairs:
<langsyntaxhighlight lang="groovy">def random = new Random()
 
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 }
Line 3,404 ⟶ 4,113:
def p = random.nextInt(factorial(n*2))
makePermutation(base, p)
}</langsyntaxhighlight>
 
Check Balance of Bracket String:
<langsyntaxhighlight lang="groovy">boolean balancedBrackets(String brackets, int depth=0) {
if (brackets == null || brackets.empty) return depth == 0
switch (brackets[0]) {
Line 3,417 ⟶ 4,126:
return brackets.size() == 1 ? depth == 0 : balancedBrackets(brackets[1..-1], depth)
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">Set brackets = []
(0..100).each {
(0..8).each { r ->
Line 3,432 ⟶ 4,141:
def bal = balancedBrackets(it) ? "balanced: " : "unbalanced: "
println "${bal} ${it}"
}</langsyntaxhighlight>
 
Output:
Line 3,631 ⟶ 4,340:
=={{header|Haskell}}==
The simplest solution exploits the idea of stack-based automaton, which could be implemented by a fold.
<langsyntaxhighlight lang="haskell">
isMatching :: String -> Bool
isMatching = null . foldl aut []
Line 3,638 ⟶ 4,347:
-- aut ('{':s) '}' = s -- automaton could be extended
aut s x = x:s
</syntaxhighlight>
</lang>
 
This generates an infinite stream of correct balanced brackets expressions:
 
<langsyntaxhighlight lang="haskell">brackets = filter isMatching
$ [1.. ] >>= (`replicateM` "[]{}") </langsyntaxhighlight>
<pre>λ> take 10 brackets
["[]","{}","[[]]","[][]","[]{}","[{}]","{[]}","{{}}","{}[]","{}{}"]</pre>
Line 3,649 ⟶ 4,358:
In case the index of unmatched opening bracket is need to be found, following solution is suitable.
 
<langsyntaxhighlight lang="haskell">
import Control.Monad
import System.Random
Line 3,680 ⟶ 4,389:
let bs = cycle "[]"
rs <- replicateM 10 newStdGen
zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2 ..] rs</langsyntaxhighlight>
We put our list shuffling function in a separate module. For efficiency we use ''mutable'' vectors, although for the short lists in our example it doesn't really matter.
<langsyntaxhighlight lang="haskell">module VShuffle
( shuffle
) where
Line 3,711 ⟶ 4,420:
do v <- V.unsafeThaw $ V.fromList xs
mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r
V.unsafeFreeze v</langsyntaxhighlight>
Here's some sample output.
<pre>
Line 3,736 ⟶ 4,445:
and '''scanl''' also yields a simple fit when we want the index of the tipping point:
 
<langsyntaxhighlight lang="haskell">import Control.Applicative ((<|>))
import Data.List (findIndex, replicate, scanl)
import Data.List.Split (chunksOf)
Line 3,742 ⟶ 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,752 ⟶ 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 3,775 ⟶ 4,486:
bracket :: Int -> Char
bracket 0 = '['
bracket _ = ']'</langsyntaxhighlight>
{{Out}}
<pre>]][]][: Unmatched
Line 3,800 ⟶ 4,511:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
every s := genbs(!arglist) do
write(image(s), if isbalanced(s) then " is balanced." else " is unbalanced")
Line 3,814 ⟶ 4,525:
every !s := ?s # shuffle
return s
end</langsyntaxhighlight>
 
Output:<pre>
Line 3,832 ⟶ 4,543:
 
=={{header|J}}==
'''Solution''': <langsyntaxhighlight lang="j">bracketDepth =: '[]' -&(+/\)/@:(=/) ]
checkBalanced =: _1 -.@e. bracketDepth
genBracketPairs =: (?~@# { ])@#"0 1&'[]' NB. bracket pairs in arbitrary order</langsyntaxhighlight>
'''Examples''':<langsyntaxhighlight lang="j"> (, ' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10
OK
][ bad
Line 3,845 ⟶ 4,556:
[[]][[][][]][] OK
]]]][[][][[[[]][ bad
[]]][][][[[[]][[]] bad</langsyntaxhighlight>
'''Comments''': This task highlights the versatility and usefulness of J's scanning modifiers, <code>/</code> and <code>\</code>.
 
Line 3,852 ⟶ 4,563:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class BalancedBrackets {
 
public static boolean hasBalancedBrackets(String str) {
Line 3,900 ⟶ 4,611:
}
}
}</langsyntaxhighlight>
Sample output (generate uses random numbers, so it should not be the same every time):
<pre>: true
Line 3,920 ⟶ 4,631:
 
=== Extended ===
<langsyntaxhighlight lang="java">import java.util.ArrayDeque;
import java.util.Deque;
 
Line 3,983 ⟶ 4,694:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>With areSquareBracketsBalanced:
Line 4,010 ⟶ 4,721:
====Iterative====
 
<langsyntaxhighlight JavaScriptlang="javascript">function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
Line 4,026 ⟶ 4,737:
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
}</langsyntaxhighlight>
 
Sample output:
Line 4,053 ⟶ 4,764:
==== Another solution ====
{{works with|Node.js}}
<syntaxhighlight lang="javascript">
<lang JavaScript>
console.log("Supplied examples");
var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"];
Line 4,110 ⟶ 4,821:
return generated;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,138 ⟶ 4,849:
====Functional====
With visual indication of where the balance fails:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 4,242 ⟶ 4,953:
// ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>'' OK
Line 4,255 ⟶ 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}}==
<langsyntaxhighlight lang="julia">using Printf
 
function balancedbrackets(str::AbstractString)
Line 4,272 ⟶ 5,067:
for (test, pass) in map(x -> (x, balancedbrackets(x)), collect(brackets(i) for i = 0:8))
@printf("%22s%10s\n", test, pass ? "pass" : "fail")
end</langsyntaxhighlight>
 
{{out}}
Line 4,286 ⟶ 5,081:
 
'''One-line version''':
<langsyntaxhighlight lang="julia">balancedbrackets(str::AbstractString) = foldl((x, y) -> x < 0 ? -1 : x + y, collect((x == '[') - (x == ']') for x in str), init = 0) == 0</langsyntaxhighlight>
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
gen_brackets:{"[]"@x _draw 2}
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)}
Line 4,304 ⟶ 5,099:
("][[][[]]][[]]]][][";0)
("]][[[[]]]][][][[]]]]";0))
</syntaxhighlight>
</lang>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">"[[]][]]"
 
%acc 0 !acc
Line 4,324 ⟶ 5,119:
print
 
" " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">import java.util.Random
 
fun isBalanced(s: String): Boolean {
Line 4,359 ⟶ 5,154:
println("$s " + if (isBalanced(s)) "OK" else "NOT OK")
}
}</langsyntaxhighlight>
Sample output (last 7 lines random) :
{{out}}
Line 4,383 ⟶ 5,178:
 
=={{header|L++}}==
<langsyntaxhighlight lang="lisp">(include "string")
(defn bool balanced (std::string s)
Line 4,397 ⟶ 5,192:
(pr std::boolalpha)
(foreach x tests
(prn x "\t" (balanced x))))</langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define randomparens(num::integer,open::string='[',close::string=']') => {
local(out) = array
 
Line 4,421 ⟶ 5,216:
with i in 1 to 10
let input = randomparens(#i)
select #input + ' = ' + validateparens(#input)</langsyntaxhighlight>
 
{{out}}
Line 4,435 ⟶ 5,230:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "Supplied examples"
for i =1 to 7
Line 4,498 ⟶ 5,293:
 
end
</syntaxhighlight>
</lang>
Supplied examples
The string '' is OK.
Line 4,521 ⟶ 5,316:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function isBalanced(s)
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.
Line 4,542 ⟶ 5,337:
print(RS)
print(isBalanced(RS))
</syntaxhighlight>
</lang>
 
=={{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}}==
This functionality is provided by Maple.
<syntaxhighlight lang="maple">
<lang Maple>
> use StringTools in
> IsBalanced( "", "[", "]" );
Line 4,578 ⟶ 5,409:
 
false
</syntaxhighlight>
</lang>
Furthermore, Maple can check whether multiple fences are balanced in the same string.
<syntaxhighlight lang="maple">
<lang Maple>
> StringTools:-IsBalanced( "[()()]", "[(", "])" );
true
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">(* Generate open/close events. *)
gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten]
 
Line 4,598 ⟶ 5,429:
Print[str <> If[match[lst, 0],
" is balanced.",
" is not balanced."]])</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight lang="matlab">function x = isbb(s)
t = cumsum((s=='[') - (s==']'));
x = all(t>=0) && (t(end)==0);
end;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,624 ⟶ 5,455:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">brack(s) := block(
[n: slength(s), r: 0, c],
catch(
Line 4,654 ⟶ 5,485:
 
brack("[[[]][]]]");
false</langsyntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module balancedbrackets.
:- interface.
Line 4,698 ⟶ 5,529:
; print(" is unbalanced\n", !IO)
).
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
 
We start by defining a function:
 
<syntaxhighlight lang="miniscript">isBalanced = function(str)
level = 0
for c in str
if c == "[" then level = level + 1
if c == "]" then level = level - 1
if level < 0 then return false
end for
return level == 0
end function</syntaxhighlight>
 
We can evaluate the example strings with this code:
 
<syntaxhighlight lang="miniscript">examples = [
"",
"[]",
"[][]",
"[[][]]",
"][",
"][][",
"[]][[]",
"[[[]"]
 
for str in examples
balanced = isBalanced(str)
if balanced then outcome = "is OK" else outcome = "NOT OK"
print """" + str + """ " + outcome
end for</syntaxhighlight>
 
{{out}}
<pre>"" is OK
"[]" is OK
"[][]" is OK
"[[][]]" is OK
"][" NOT OK
"][][" NOT OK
"[]][[]" NOT OK
"[[[]" NOT OK</pre>
 
=={{header|Modula-2}}==
{{works with|TopSpeed (JPI) Modula-2 under DOSBox-X}}
An interesting point is how to ensure that all strings of N left plus N right brackets are equally likely. The program below shows one way of doing this.
<langsyntaxhighlight lang="modula2">
MODULE Brackets;
IMPORT IO, Lib;
Line 4,751 ⟶ 5,624:
END;
END Brackets.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,768 ⟶ 5,641:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.Util
 
def gen(N)
Line 4,800 ⟶ 5,673:
println format("%-22s is not balanced", txt)
end
end</langsyntaxhighlight>
{{out}}
<pre> is balanced
Line 4,815 ⟶ 5,688:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">
from random import random, randomize, shuffle
from strutils import repeat
Line 4,839 ⟶ 5,712:
for n in 0..9:
let s = gen(n)
echo "'", s, "' is ", (if balanced(s): "balanced" else: "not balanced")</langsyntaxhighlight>
Output:
<pre>'' is balanced
Line 4,851 ⟶ 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}}==
{{works with|oo2c version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE BalancedBrackets;
IMPORT
Line 4,957 ⟶ 5,863:
Do
END BalancedBrackets.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,969 ⟶ 5,875:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Balanced {
Line 5,002 ⟶ 5,908:
}
}
</syntaxhighlight>
</lang>
<pre>
: true
Line 5,015 ⟶ 5,921:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let generate_brackets n =
let rec aux i acc =
if i <= 0 then acc else
Line 5,039 ⟶ 5,945:
List.iter print_char brk;
Printf.printf " %B\n" (is_balanced brk);
;;</langsyntaxhighlight>
 
<pre>
Line 5,050 ⟶ 5,956:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">String method: isBalanced
| c |
0 self forEach: c [
Line 5,060 ⟶ 5,966:
: genBrackets(n)
"" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ;</langsyntaxhighlight>
 
{{out}}
Line 5,078 ⟶ 5,984:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
 
Line 5,126 ⟶ 6,032:
end
return answer~string
</syntaxhighlight>
</lang>
Sample output (uses randomly generated groupings, so it should be different on each run):
<pre>
Line 5,147 ⟶ 6,053:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">function CheckBrackets(string s) as bool
'=======================================
sys co, le=len s
Line 5,174 ⟶ 6,080:
print CheckBrackets "[][]"'1
print CheckBrackets "][" '0
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">balanced(s)={
my(n=0,v=Vecsmall(s));
for(i=1,#v,
Line 5,189 ⟶ 6,095:
};
rnd(n)=Strchr(vectorsmall(n,i,if(random(2),91,93)))
forstep(n=0,10,2,s=rnd(n);print(s"\t"if(balanced(s),"true","false")))</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 5,198 ⟶ 6,104:
Idiomatic solution, using a regex that performs subpattern recursion ''(works with Perl 5.10 and newer)'':
 
<langsyntaxhighlight Perllang="perl">sub generate {
my $n = shift;
my $str = '[' x $n;
Line 5,212 ⟶ 6,118:
my $input = generate($_);
print balanced($input) ? " ok:" : "bad:", " '$input'\n";
}</langsyntaxhighlight>
 
{{out}}
Line 5,229 ⟶ 6,135:
If input strings are allowed to contain unrelated characters, this can be extended to:
 
<langsyntaxhighlight Perllang="perl">sub balanced {
shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x;
}</langsyntaxhighlight>
 
<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)
 
<langsyntaxhighlight Perllang="perl">use Regexp::Common 'balancedRE_balanced';
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/;
sub balanced {
return shift =~ $re;RE_balanced(-parens=>'[]')
}
}</lang>
</syntaxhighlight>
 
Alternative implementation, using straightforward depth counting:
 
<langsyntaxhighlight Perllang="perl">sub balanced {
my $depth = 0;
for (split //, shift) {
Line 5,250 ⟶ 6,156:
}
return !$depth
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function check_brackets(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer level = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">check_brackets</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">level</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
switch s[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
case '[': level += 1
<span style="color: #008080;">switch</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
case ']': level -= 1
<span style="color: #008080;">case</span> <span style="color: #008000;">'['</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">level</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if level<0 then exit end if
<span style="color: #008080;">case</span> <span style="color: #008000;">']'</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">level</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
end switch
<span style="color: #008080;">if</span> <span style="color: #000000;">level</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
return (level=0)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">level</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence s
constant ok = {"not ok","ok"}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">ok</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"not ok"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ok"</span><span style="color: #0000FF;">}</span>
for i=1 to 10 do
for j=1 to 2 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
s = shuffle(join(repeat("[]",i-1),""))
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
printf(1,"%s %s\n",{s,ok[check_brackets(s)+1]})
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"[]"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">))</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ok</span><span style="color: #0000FF;">[</span><span style="color: #000000;">check_brackets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]})</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 5,299 ⟶ 6,208:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"[[]][]"
0 var acc
 
Line 5,315 ⟶ 6,224:
" is OK"
endif
print</langsyntaxhighlight>
 
=={{header|PHP}}==
The sample is given as unix shell script, you need to have ''php-cli'' (or what your package manager calls it) installed.
 
<langsyntaxhighlight PHPlang="php">#!/usr/bin/php
<?php
 
Line 5,353 ⟶ 6,262:
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL);
}
</syntaxhighlight>
</lang>
Sample run:
<pre>
Line 5,368 ⟶ 6,277:
[[[][]]] OK
</pre>
 
=={{header|Picat}}==
===Foreach loop===
<syntaxhighlight lang="picat">go1 ?=>
tests(Tests),
member(Test,Tests),
printf("%s: ", Test),
( balanced_brackets(Test) ->
println("OK")
;
println("NOT OK")
),
fail,
nl.
go1 => true.
 
% Check if a string of [] is balanced
balanced_brackets(B) =>
C = 0,
foreach(I in 1..B.length, C >= 0)
C:= C + cond(B[I] = '[', 1, -1)
end,
C == 0.
 
tests(["","[]", "[][]", "[[][]]", "][",
"][][", "[]][[]", "[][][][][][][][][][]",
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]",
"[][[]][]","[[][]][]", "[][][[]][]"]).</syntaxhighlight>
 
{{out}}
<pre>: OK
[]: OK
[][]: OK
[[][]]: OK
][: NOT OK
][][: NOT OK
[]][[]: NOT OK
[][][][][][][][][][]: OK
[[[[[[[]]]]]]]: OK
[[[[[[[]]]]]]: NOT OK
[][[]][]: OK
[[][]][]: OK
[][][[]][]: OK</pre>
 
===DCG===
Here is an implementation using DCG (Definite Clause Grammars).
<syntaxhighlight lang="picat">go_dcg ?=>
tests(Tests),
foreach(Test in Tests)
printf("%s: ", Test),
if balanced(Test,[]) then
println("OK")
else
println("NOT OK")
end
end,
nl.
go_dcg => true.
 
balanced --> "".
balanced --> "[", balanced, "]", balanced.</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l") # For 'shuffle'
 
(de generateBrackets (N)
Line 5,386 ⟶ 6,356:
 
(for N 10
(prinl (if (checkBrackets (prin (generateBrackets N))) " OK" "not OK")) )</langsyntaxhighlight>
Output:
<pre>[] OK
Line 5,400 ⟶ 6,370:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process m or(!) s attributes source;
cb: Proc Options(main);
/* PL/I program to check for balanced brackets [] ********************
Line 5,461 ⟶ 6,431:
End;
 
End;</langsyntaxhighlight>
Output:
<pre> balanced ''
Line 5,492 ⟶ 6,462:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-BalanceStatus ( $String )
{
Line 5,511 ⟶ 6,481:
return $Status
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
# Test
$Strings = @( "" )
Line 5,521 ⟶ 6,491:
$String.PadRight( 12, " " ) + (Get-BalanceStatus $String)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,534 ⟶ 6,504:
 
===PowerShell (Regex Version)===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-BalancedBracket
{
Line 5,592 ⟶ 6,562:
"{0}: {1}" -f $s.PadRight(8), "$(if (Test-BalancedBracket Brace $s) {'Is balanced.'} else {'Is not balanced.'})"
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,606 ⟶ 6,576:
=={{header|Prolog}}==
DCG are very usefull for this kind of exercice !
<langsyntaxhighlight Prologlang="prolog">rosetta_brackets :-
test_brackets([]),
test_brackets(['[',']']),
Line 5,658 ⟶ 6,628:
bracket(0) --> ['['].
bracket(1) --> [']'].
</syntaxhighlight>
</lang>
Sample output :
<pre> ?- balanced_brackets.
Line 5,685 ⟶ 6,655:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s Generate(N)
For i=1 To N
sample$+"[]"
Line 5,728 ⟶ 6,698:
PrintN(" is not balanced")
EndIf
Next</langsyntaxhighlight>
Output sample
<pre>
Line 5,740 ⟶ 6,710:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def gen(N):
... txt = ['[', ']'] * N
... random.shuffle( txt )
Line 5,766 ⟶ 6,736:
'[[]]]]][]][[[[' is not balanced
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced</langsyntaxhighlight>
 
=== Functional ===
Line 5,772 ⟶ 6,742:
Rather than explicitly track the count, we can just write the per-element test and use stdlib functions to turn it into a whole-sequence test. It's straightforwardly declarative, and hard to get wrong, but whether it's actually easier to understand depends on how familiar the reader is with thinking in `itertools` style.
 
<langsyntaxhighlight lang="python">>>> from itertools import accumulate
>>> from random import shuffle
>>> def gen(n):
Line 5,795 ⟶ 6,765:
'][]][][[]][[][' is not balanced
'][[]]][][[]][[[]' is not balanced
'][[][[]]]][[[]][][' is not balanced</langsyntaxhighlight>
 
=== Array Programming ===
Line 5,801 ⟶ 6,771:
The numpy library gives us a way to write just the elementwise tests and automatically turn them into whole-sequence tests, although it can be a bit clumsy to use for character rather than numeric operations. The simplicity of the final expression probably doesn't make up for all that extra clumsiness in this case.
 
<langsyntaxhighlight lang="python">>>> import numpy as np
>>> from random import shuffle
>>> def gen(n):
Line 5,825 ⟶ 6,795:
'[][[[]][[]]][]' is balanced
'[[][][[]]][[[]]]' is balanced
'][]][][[]][]][][[[' is not balanced</langsyntaxhighlight>
 
=={{header|Qi}}==
 
<langsyntaxhighlight lang="qi">(define balanced-brackets-0
[] 0 -> true
[] _ -> false
Line 5,851 ⟶ 6,821:
(balanced-brackets "[]][[]")
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ char [ over of
swap
char ] swap of
Line 5,875 ⟶ 6,845:
[ say "un" ]
say "balanced."
cr ]</langsyntaxhighlight>
 
{{out}}
Line 5,894 ⟶ 6,864:
=={{header|R}}==
 
<langsyntaxhighlight lang="r">balanced <- function(str){
str <- strsplit(str, "")[[1]]
str <- ifelse(str=='[', 1, -1)
all(cumsum(str) >= 0) && sum(str) == 0
}</langsyntaxhighlight>
 
Alternately, using perl 5.10-compatible regexps,
 
<langsyntaxhighlight lang="r">balanced <- function(str) {
regexpr('^(\\[(?1)*\\])*$', str, perl=TRUE) > -1
}</langsyntaxhighlight>
 
To generate some some examples:
 
<langsyntaxhighlight Rlang="r">rand.parens <- function(n) paste(sample(c("[","]"),2*n,replace=T),collapse="")
 
as.data.frame(within(list(), {
parens <- replicate(10, rand.parens(sample.int(10,size=1)))
balanced <- sapply(parens, balanced)
}))</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight lang="r"> balanced parens
1 FALSE ][][
2 FALSE [][[]]][[]][]]][[[
Line 5,926 ⟶ 6,896:
8 FALSE []]]][[[]][[[]
9 TRUE [[[[][[][]]]]]
10 TRUE []</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 5,948 ⟶ 6,918:
 
(for ([n 10]) (try n))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,957 ⟶ 6,927:
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" perl6line>sub balanced($s) {
my $l = 0;
for $s.comb {
Line 5,973 ⟶ 6,943:
my $n = prompt "Number of brackets";
my $s = (<[ ]> xx $n).flat.pick(*).join;
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</langsyntaxhighlight>
 
===FP oriented===
Here's a more idiomatic solution using a hyperoperator to compare all the characters to a backslash (which is between the brackets in ASCII), a triangle reduction to return the running sum, a <tt>given</tt> to make that list the topic, and then a topicalized junction and a topicalized subscript to test the criteria for balance.
<syntaxhighlight lang="raku" perl6line>sub balanced($s) {
.none < 0 and .[*-1] == 0
given ([\+] '\\' «leg« $s.comb).cache;
Line 5,984 ⟶ 6,954:
my $n = prompt "Number of bracket pairs: ";
my $s = <[ ]>.roll($n*2).join;
say "$s { balanced($s) ?? "is" !! "is not" } well-balanced"</langsyntaxhighlight>
 
===String munging===
Of course, a Perl 5 programmer might just remove as many inner balanced pairs as possible and then see what's left.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>sub balanced($_ is copy) {
Nil while s:g/'[]'//;
$_ eq '';
Line 5,996 ⟶ 6,966:
my $n = prompt "Number of bracket pairs: ";
my $s = <[ ]>.roll($n*2).join;
say "$s is", ' not' x not balanced($s), " well-balanced";</langsyntaxhighlight>
 
===Parsing with a grammar===
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>grammar BalBrack { token TOP { '[' <TOP>* ']' } }
 
my $n = prompt "Number of bracket pairs: ";
my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join;
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">; Functional code
balanced-brackets: [#"[" any balanced-brackets #"]"]
rule: [any balanced-brackets end]
Line 6,028 ⟶ 6,998:
str: random copy/part "[][][][][][][][][][]" i * 2
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]]
]</langsyntaxhighlight>
 
=={{header|REXX}}==
===with 40 examples===
<langsyntaxhighlight lang="rexx">/*REXX program checks for balanced brackets [ ] ─── some fixed, others random.*/
parse arg seed . /*obtain optional argument from the CL.*/
if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/
Line 6,070 ⟶ 7,040:
else do; !=!-1; if !<0 then return 0; end
end /*j*/
return !==0 /* [↑] "!" is the nested ][ counter.*/</langsyntaxhighlight>
'''output''' &nbsp; using the (some internal, others random) expressions:
<pre>
Line 6,116 ⟶ 7,086:
 
===with examples + 30 permutations===
<langsyntaxhighlight lang="rexx">
/*REXX program to check for balanced brackets [] **********************
* test strings and random string generation copied from Version 1
Line 6,184 ⟶ 7,154:
end
return nest=0 /* nest=0 -> balanced */
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,233 ⟶ 7,203:
Naturally, each of the one hundred thousand character strings aren't displayed (for balanced/not-balanced),
<br>but a count is displayed, as anyone can generate the same strings in other languages and compare results.
<langsyntaxhighlight lang="rexx">/*REXX program checks for around 125,000 generated balanced brackets expressions [ ] */
bals=0
#=0; do j=1 until L>20 /*generate lots of bracket permutations*/
Line 6,253 ⟶ 7,223:
/*──────────────────────────────────────────────────────────────────────────────────────*/
countStr: procedure; parse arg n,h,s; if s=='' then s=1; w=length(n)
do r=0 until _==0; _=pos(n,h,s); s=_+w; end; return r</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 6,260 ⟶ 7,230:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nr = 0
while nr < 10
Line 6,287 ⟶ 7,257:
next
return "ok."
</syntaxhighlight>
</lang>
Output:
<pre>
Line 6,300 ⟶ 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 6,305 ⟶ 7,304:
{{trans|D}}
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby">re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
Line 6,321 ⟶ 7,320:
t = s.gsub(/[^\[\]]/, "")
puts (t =~ re ? " OK: " : "bad: ") + s
end</langsyntaxhighlight>
 
One output: <pre>
Line 6,340 ⟶ 7,339:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim brk$(10)
brk$(1) = "[[[][]]]"
brk$(2) = "[[[]][[[][[][]]]]]"
Line 6,360 ⟶ 7,359:
if trim$(b$) = "" then print " OK "; else print "Not OK ";
print brk$(i)
next i</langsyntaxhighlight>
 
One output: <pre> OK
Line 6,378 ⟶ 7,377:
 
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
trait Balanced {
Line 6,417 ⟶ 7,416:
println!("{} {}", brackets, brackets.is_balanced())
}
}</langsyntaxhighlight>
Output: <pre>
true
Line 6,437 ⟶ 7,436:
=== Scala Version 1 ===
{{works with|Scala|2.9.1}}
<langsyntaxhighlight lang="scala">import scala.collection.mutable.ListBuffer
import scala.util.Random
 
Line 6,472 ⟶ 7,471:
println("\n"+"check all permutations of given length:")
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
}</langsyntaxhighlight>
 
<pre style="height:30ex;overflow:scroll">arbitrary random order:
Line 6,848 ⟶ 7,847:
=== Scala Version 2 ===
{{works with|Scala|2.10.1}}
<langsyntaxhighlight lang="scala">import scala.util.Random.shuffle
 
object BalancedBracketsApp extends App {
Line 6,875 ⟶ 7,874:
}
 
}</langsyntaxhighlight>
 
Alternate implementation of "isBalanced" using tail-recursion instead of var and return:
 
<langsyntaxhighlight lang="scala">import scala.util.Random.shuffle
import scala.annotation.tailrec
 
Line 6,898 ⟶ 7,897:
isBalanced(rest, newBalance)
}
</syntaxhighlight>
</lang>
 
Slightly modified implementation of "isBalanced" using tail-recursion
{{works with|Scala|2.11.7}}
<langsyntaxhighlight lang="scala">
@scala.annotation.tailrec
final def isBalanced(
Line 6,921 ⟶ 7,920:
}
}
</syntaxhighlight>
</lang>
 
Sample output:
Line 6,938 ⟶ 7,937:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (balanced-brackets string)
(define (b chars sum)
(cond ((< sum 0)
Line 6,963 ⟶ 7,962:
(balanced-brackets "][][")
(balanced-brackets "[]][[]")
</syntaxhighlight>
</lang>
 
=={{header|Scilab}}==
{{trans|MATLAB}}
<syntaxhighlight lang="text">function varargout=isbb(s)
st=strsplit(s);
t=cumsum((st=='[')-(st==']'));
balanced=and(t>=0) & t(length(t))==0;
varargout=list(balanced)
endfunction</langsyntaxhighlight>
{{out}}
The following code was used to generate random strings of length 5, 16, and 22 chars. It also displays the generated string, and the output (true of false) of <code>isbb()</code>.
<syntaxhighlight lang="text">for j=[5 16 22]
s=[];
for i=1:j
Line 6,988 ⟶ 7,987:
x=isbb(s);
disp(x);
end</langsyntaxhighlight>
Console output:
<pre> ][]][
Line 7,003 ⟶ 8,002:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: generateBrackets (in integer: count) is func
Line 7,055 ⟶ 8,054:
end for;
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 7,076 ⟶ 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}}==
<langsyntaxhighlight lang="ruby">func balanced (str) {
 
var depth = 0
Line 7,090 ⟶ 8,132:
for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] {
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str)
}</langsyntaxhighlight>
 
{{out}}
Line 7,104 ⟶ 8,146:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER U;
U := ININT;
Line 7,149 ⟶ 8,191:
 
END;
END</langsyntaxhighlight>
{{in}}
<pre>710</pre>
Line 7,199 ⟶ 8,241:
{{works with|PolyML}}
 
<langsyntaxhighlight lang="sml">fun isBalanced s = checkBrackets 0 (String.explode s)
and checkBrackets 0 [] = true
| checkBrackets _ [] = false
Line 7,205 ⟶ 8,247:
| checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest
| checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest
| checkBrackets counter (_::rest) = checkBrackets counter rest</langsyntaxhighlight>
 
An example of usage
 
<langsyntaxhighlight lang="sml">val () =
List.app print
(List.map
Line 7,219 ⟶ 8,261:
(* A set of strings to test *)
["", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"]
)</langsyntaxhighlight>
 
Output:
Line 7,234 ⟶ 8,276:
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">mata
function random_brackets(n) {
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],""))
Line 7,245 ⟶ 8,287:
return(all(a:>=0) & a[n]==0)
}
end</langsyntaxhighlight>
 
'''Test'''
Line 7,272 ⟶ 8,314:
Checks balance function:
 
<langsyntaxhighlight lang="swift">import Foundation
 
func isBal(str: String) -> Bool {
Line 7,281 ⟶ 8,323:
}
</langsyntaxhighlight>output:<syntaxhighlight lang ="swift">
isBal("[[[]]]") // true
 
isBal("[]][[]") // false
 
</langsyntaxhighlight>Random Bracket function:<syntaxhighlight lang ="swift">
 
func randBrack(n: Int) -> String {
Line 7,302 ⟶ 8,344:
}
 
</langsyntaxhighlight>output:<syntaxhighlight lang ="swift">
 
randBrack(2) // "]][["
 
</langsyntaxhighlight>Random check balance function:<syntaxhighlight lang ="swift">
 
func randIsBal(n: Int) {
Line 7,321 ⟶ 8,363:
randIsBal(4)
 
</langsyntaxhighlight>output:<syntaxhighlight lang ="swift">
 
// ][ is unbalanced
Line 7,329 ⟶ 8,371:
// []][[] is unbalanced
//
// [][][[]] is balanced</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc generate {n} {
if {!$n} return
set l [lrepeat $n "\[" "\]"]
Line 7,359 ⟶ 8,401:
set s [generate $i]
puts "\"$s\"\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]"
}</langsyntaxhighlight>
Sample output:
<pre>
Line 7,380 ⟶ 8,422:
===Constructing correctly balanced strings===
It is, of course, possible to directly construct such a balanced string, this being much more useful as the length of the string to generate grows longer. This is done by conceptually building a random tree (or forest) and then walking the tree, with open brackets being appended when a node is entered from its root and close brackets being appended when a node is left for its root. This is equivalent to inserting a balanced pair of brackets at a random place in an initially-empty string <math>n</math> times, which might be done like this:
<langsyntaxhighlight lang="tcl">proc constructBalancedString {n} {
set s ""
for {set i 0} {$i < $n} {incr i} {
Line 7,387 ⟶ 8,429:
}
return $s
}</langsyntaxhighlight>
As noted, because the generated string is guaranteed to be balanced, it requires no further filtering and this results in much more efficient generation of balanced strings at longer lengths (because there's no need to backtrack).
 
Line 7,394 ⟶ 8,436:
 
Generation program in Unix TMG:
<langsyntaxhighlight UnixTMGlang="unixtmg">program: readint(n) [n>0] readint(seed)
loop: parse(render) [--n>0?]/done loop;
render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * };
Line 7,412 ⟶ 8,454:
>>;
 
n: 0; i: 0; b: 0; seed: 0;</langsyntaxhighlight>
 
Sample output:
Line 7,422 ⟶ 8,464:
 
Analysis can be done easily using grammar specification, rather than counting brackets:
<langsyntaxhighlight UnixTMGlang="unixtmg">loop: parse(corr)\loop parse(incorr)\loop;
corr: brkts * = { < OK: > 1 * };
brkts: brkt/null brkts = { 2 1 };
Line 7,432 ⟶ 8,474:
 
nonl: !<<
>>;</langsyntaxhighlight>
 
Sample output:
Line 7,445 ⟶ 8,487:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 7,475 ⟶ 8,517:
PRINT b," ",status
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 7,495 ⟶ 8,537:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end)
@(do (defvar r (make-random-state nil))
 
Line 7,517 ⟶ 8,559:
@{parens 15} @{matched 15} @{mismatched 15}
@ (end)
@(end)</langsyntaxhighlight>
 
The recursive pattern function <code>@(paren)</code> gives rise to a grammar which matches parentheses:
Line 7,551 ⟶ 8,593:
][[[[]]]][][ ][[[[]]]][][
[[]]]]][[][[ [[]] ]]][[][[ </pre>
 
== {{header|TypeScript}} ==
{{trans|JavaScript}}
<syntaxhighlight lang="javascript">// Balanced brackets
 
function isStringBalanced(str: string): bool {
var paired = 0;
for (var i = 0; i < str.length && paired >= 0; i++) {
var c = str.charAt(i);
if (c == '[')
paired++;
else if (c == ']')
paired--;
}
return (paired == 0);
}
function generate(n: number): string {
var opensCount = 0, closesCount = 0;
// Choose at random until n of one type generated
var generated: string[] = new Array(); // Works like StringBuilder
while (opensCount < n && closesCount < n) {
if (Math.floor(Math.random() * 2) == 0) {
++opensCount;
generated.push("[");
} else {
++closesCount;
generated.push("]");
}
}
// Now pad with the remaining other brackets
generated.push(opensCount == n ?
"]".repeat(n - closesCount) :
"[".repeat(n - opensCount));
return generated.join("");
}
 
console.log("Supplied examples");
var tests: string[] = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"];
for (var test of tests)
console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK."));
console.log();
console.log("Random generated examples");
for (var example = 0; example < 10; example++) {
var test = generate(Math.floor(Math.random() * 10) + 1);
console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK.")}`);
}
</syntaxhighlight>
{{out}}
<pre>
Supplied examples
The string '' is OK.
The string '[]' is OK.
The string '][' is not OK.
The string '[][]' is OK.
The string '][][' is not OK.
The string '[[][]]' is OK.
The string '[]][[]' is not OK.
 
Random generated examples
The string ']]][[[][' is not OK.
The string '][][][[[[]]]' is not OK.
The string ']][[[[]]' is not OK.
The string '][]]]]]][][][][[[[[[' is not OK.
The string '][[[][][[[]]]]' is not OK.
The string '[[[]]]' is OK.
The string ']]]][[[[[]' is not OK.
The string '][[]]]]][[[][[]]][[[' is not OK.
The string ']]]][]][[[[[' is not OK.
The string '[[[[[[]]]]]]' is OK.
</pre>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang="bash">generate() {
local b=()
local i j tmp
Line 7,591 ⟶ 8,704:
balanced "$test" && result=OK || result="NOT OK"
printf "%s\t%s\n" "$test" "$result"
done</langsyntaxhighlight>
 
{{output}}
Line 7,608 ⟶ 8,721:
=={{header|Ursala}}==
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 7,615 ⟶ 8,728:
#cast %bm
 
main = ^(2-$'[]'*,balanced)* eql@ZFiFX*~ iota64</langsyntaxhighlight>
output:
<pre><
Line 7,635 ⟶ 8,748:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Public Function checkBrackets(s As String) As Boolean
'function checks strings for balanced brackets
Line 7,702 ⟶ 8,815:
Next
End Sub
</syntaxhighlight>
</lang>
 
sample output:
Line 7,719 ⟶ 8,832:
"]][][[[][]]][][[][][": Not OK
</pre>
{{omit from|GUISS}}
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">For n = 1 To 10
sequence = Generate_Sequence(n)
WScript.Echo sequence & " is " & Check_Balance(sequence) & "."
Line 7,757 ⟶ 8,869:
Check_Balance = "Balanced"
End If
End Function</langsyntaxhighlight>
 
{{out}}
Line 7,772 ⟶ 8,884:
]][][]][] is Not Balanced.
[[][[[[[]] is Not Balanced.</pre>
 
Antother version not using libraries. The generator works as intended (more difficult to do than the checking)
<syntaxhighlight lang="vb">
option explicit
 
function do_brackets(bal)
dim s,i,cnt,r
if bal then s="[":cnt=1 else s="":cnt=0
for i=1 to 20
if (rnd>0.7) then r=not r
if not r then
s=s+"[" :cnt=cnt+1
else
if not bal or (bal and cnt>0) then s=s+"]":cnt=cnt-1
end if
next
if bal and cnt<>0 then s=s&string(cnt,"]")
if not bal and cnt=0 then s=s&"]"
do_brackets=s
end function
 
function isbalanced(s)
dim s1,i,cnt: cnt=0
for i=1 to len(s)
s1=mid(s,i,1)
if s1="[" then cnt=cnt+1
if s1="]" then cnt=cnt-1
if cnt<0 then isbalanced=false:exit function
next
isbalanced=(cnt=0)
end function
 
function iif(a,b,c): if a then iif=b else iif=c end if : end function
 
randomize timer
dim i,s,bal,bb
for i=1 to 10
bal=(rnd>.5)
s=do_brackets(bal)
bb=isbalanced(s)
wscript.echo iif (bal,"","un")& "balanced string " &vbtab _
& s & vbtab & " Checks as " & iif(bb,"","un")&"balanced"
next
</syntaxhighlight>
Sample run
<pre>
unbalanced string [[[[[[[[][[][[[[[]][ Checks as unbalanced
balanced string [[[]]][[[[[[[]][]]]]]] Checks as balanced
balanced string [[[]][]][[[[[]]]]] Checks as balanced
unbalanced string ][][]][[[[]]][]]]]]] Checks as unbalanced
balanced string [[][[[[[[[[]]][[[[[[[]]]]]]]]]]]]] Checks as balanced
balanced string [[]][][[[[[]]]]] Checks as balanced
balanced string [][[]][][][[[[[[]]]]]] Checks as balanced
balanced string [[[[[[[]][[[[[[[[[][[]]]]]]]]]]]]]]] Checks as balanced
unbalanced string [[]]][[[[[[]]]]]][][] Checks as unbalanced
balanced string [[[[[[][[[[[]]]]]]]]]] Checks as balanced
</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Module1
 
Private rand As New Random
Line 7,817 ⟶ 8,986:
Return numOpen = numClosed
End Function
End Module</langsyntaxhighlight>
 
{{out}}
Line 7,831 ⟶ 9,000:
: OK
[] : OK
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import datatypes as dt
 
fn is_valid(bracket string) bool {
mut s := dt.Stack<string>{}
for b in bracket.split('') {
if b == '[' {
s.push(b)
} else {
if s.peek() or {''} == '[' {
s.pop() or {panic("WON'T GET HERE EVER")}
} else {
return false
}
}
}
return true
}
 
fn main() {
brackets := ['','[]','[][]','[[][]]','][','][][','[]][[]','[][[][[]][][[][]]]']
for b in brackets {
println('$b ${is_valid(b)}')
}
}</syntaxhighlight>
 
{{out}}
<pre>
true
[] true
[][] true
[[][]] true
][ false
][][ false
[]][[] false
[][[][[]][][[][]]] true
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var isBalanced = Fn.new { |s|
Line 7,864 ⟶ 9,071:
for (j in 1..8) s = s + ((rand.int(2) == 0) ? "[" : "]")
System.print("%(s) %(isBalanced.call(s) ? "OK" : "NOT OK")")
}</langsyntaxhighlight>
 
{{out}}
Line 7,888 ⟶ 9,095:
 
=={{header|X86 Assembly}}==
<syntaxhighlight lang="x86assembly">
<lang X86Assembly>
section .data
 
Line 7,955 ⟶ 9,162:
syscall
ret
</syntaxhighlight>
</lang>
 
=={{header|XBasic}}==
{{trans|JavaScript}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Balanced brackets
<lang xbasic>
PROGRAM "balancedbrackets"
VERSION "0.001"
Line 8,059 ⟶ 9,266:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,085 ⟶ 9,292:
 
=={{header|XBS}}==
<langsyntaxhighlight lang="xbs">const Chars:[string] = ["[","]"];
func GenerateString(Amount:number=4):string{
set Result:string = "";
Line 8,101 ⟶ 9,308:
set s = GenerateString(math.random(2,4)*2);
log(`{s}: {IsBalanced(s)}`);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 8,117 ⟶ 9,324:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic code declarations
 
int N, I, C, Nest;
Line 8,142 ⟶ 9,349:
Text(0,"OK
");
]</langsyntaxhighlight>
 
Example output:
Line 8,154 ⟶ 9,361:
 
=={{header|Ya}}==
<langsyntaxhighlight Yalang="ya">@Balanced[]s // each source must be started by specifying its file name; std extension .Ya could be ommitted and auto added by compiler
 
// all types are prefixed by `
Line 8,190 ⟶ 9,397:
//@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop
@Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad")
// note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub check_brackets(s$)
local level, i
Line 8,210 ⟶ 9,417:
 
if not check_brackets(s$) print "not ";
print "ok"</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn bb(bs){ while(a:=bs.span("[","]")) {bs=bs[a[1],*]} (Void!=a) }</langsyntaxhighlight>
The span method finds the start and length of a balanced span. This algorithm assumes the string only contains brackets; a matched span is chopped off the front of the string and a new balanced span is searched for. Stops when the string is empty or unbalanced (span returns Void).
<pre>
Line 8,234 ⟶ 9,441:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang="zxbasic">10 FOR n=1 TO 7
20 READ s$
25 PRINT "The sequence ";s$;" is ";
Line 8,251 ⟶ 9,458:
1100 RETURN
2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][]["
</syntaxhighlight>
</lang>
{{omit from|GUISS}}
Anonymous user