Balanced brackets: Difference between revisions
Content added Content deleted
(→{{header|TypeScript}}: Added.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 19: | Line 19: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F gen(n) |
||
V txt = [‘[’, ‘]’] * n |
V txt = [‘[’, ‘]’] * n |
||
random:shuffle(&txt) |
random:shuffle(&txt) |
||
Line 37: | Line 37: | ||
L(n) 0..9 |
L(n) 0..9 |
||
V s = gen(n) |
V s = gen(n) |
||
print(s‘’(‘ ’ * (20 - s.len))‘is ’(I is_balanced(s) {‘balanced’} E ‘not balanced’))</ |
print(s‘’(‘ ’ * (20 - s.len))‘is ’(I is_balanced(s) {‘balanced’} E ‘not balanced’))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 53: | Line 53: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang=360asm>* Balanced brackets 28/04/2016 |
||
BALANCE CSECT |
BALANCE CSECT |
||
USING BALANCE,R13 base register and savearea pointer |
USING BALANCE,R13 base register and savearea pointer |
||
Line 153: | Line 153: | ||
XDEC DS CL12 |
XDEC DS CL12 |
||
REGS |
REGS |
||
END BALANCE</ |
END BALANCE</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 179: | Line 179: | ||
=={{header|ABAP}}== |
=={{header|ABAP}}== |
||
< |
<syntaxhighlight lang=ABAP> |
||
CLASS lcl_balanced_brackets DEFINITION. |
CLASS lcl_balanced_brackets DEFINITION. |
||
PUBLIC SECTION. |
PUBLIC SECTION. |
||
Line 276: | Line 276: | ||
cl_demo_output=>display( ). |
cl_demo_output=>display( ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 303: | Line 303: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang=Action!>PROC Generate(BYTE size CHAR ARRAY s) |
||
BYTE i,half |
BYTE i,half |
||
Line 374: | Line 374: | ||
PrintE("balanced") |
PrintE("balanced") |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Balanced_brackets.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Balanced_brackets.png Screenshot from Atari 8-bit computer] |
||
Line 395: | Line 395: | ||
Using #HASH-OFF |
Using #HASH-OFF |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang=Acurity Architect> |
||
FUNCTION bBRACKETS_MATCH(zStringWithBrackets: STRING): STRING |
FUNCTION bBRACKETS_MATCH(zStringWithBrackets: STRING): STRING |
||
VAR sCount: SHORT |
VAR sCount: SHORT |
||
Line 415: | Line 415: | ||
RETURN zOK |
RETURN zOK |
||
ENDFUNCTION |
ENDFUNCTION |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 426: | Line 426: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
brackets.adb: |
brackets.adb: |
||
< |
<syntaxhighlight lang=Ada>with Ada.Numerics.Discrete_Random; |
||
with Ada.Text_IO; |
with Ada.Text_IO; |
||
with Ada.Strings.Fixed; |
with Ada.Strings.Fixed; |
||
Line 482: | Line 482: | ||
end loop; |
end loop; |
||
end loop; |
end loop; |
||
end Brackets;</ |
end Brackets;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 503: | Line 503: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang=aime>unbalanced(data s) |
||
{ |
{ |
||
integer b, i; |
integer b, i; |
||
Line 537: | Line 537: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> is balanced |
<pre> is balanced |
||
Line 552: | Line 552: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
||
< |
<syntaxhighlight lang=algol68># generates a string of random opening and closing brackets. The number of # |
||
# each type of brackets is speccified in length # |
# each type of brackets is speccified in length # |
||
PROC get brackets = ( INT length ) STRING: |
PROC get brackets = ( INT length ) STRING: |
||
Line 614: | Line 614: | ||
test check brackets( get brackets( length ) ) |
test check brackets( get brackets( length ) ) |
||
OD |
OD |
||
OD</ |
OD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 649: | Line 649: | ||
<br clear=both> |
<br clear=both> |
||
==={{header|Java}}=== |
==={{header|Java}}=== |
||
<lang> |
<syntaxhighlight lang=text> |
||
grammar balancedBrackets ; |
grammar balancedBrackets ; |
||
Line 669: | Line 669: | ||
NEWLINE : '\r'? '\n' |
NEWLINE : '\r'? '\n' |
||
; |
; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Produces: |
Produces: |
||
<pre> |
<pre> |
||
Line 694: | Line 694: | ||
and a function to check whether a given string of brackets is balanced. |
and a function to check whether a given string of brackets is balanced. |
||
< |
<syntaxhighlight lang=APL>gen ← (⊂+?+)⍨ ⌷ ('[]'/⍨⊢) |
||
bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢)</ |
bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢)</syntaxhighlight> |
||
Sample run for 0..N..10: |
Sample run for 0..N..10: |
||
< |
<syntaxhighlight lang=APL> ↑{br←gen ⍵ ⋄ br,': ',(1+bal br)⊃'Bad' 'Good'}¨0,⍳10 |
||
: Good |
: Good |
||
[]: Good |
[]: Good |
||
Line 710: | Line 710: | ||
[[][[]]][[[[]]]]: Good |
[[][[]]][[[[]]]]: Good |
||
[[[]][[[[][]][]]]]: Good |
[[[]][[[[][]][]]]]: Good |
||
]][][][][[][][]][[[]: Bad</ |
]][][][][[][][]][[[]: Bad</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Line 717: | Line 717: | ||
(ES6 functionally composed version) |
(ES6 functionally composed version) |
||
< |
<syntaxhighlight lang=AppleScript>-- CHECK NESTING OF SQUARE BRACKET SEQUENCES --------------------------------- |
||
-- Zero-based index of the first problem (-1 if none found): |
-- Zero-based index of the first problem (-1 if none found): |
||
Line 899: | Line 899: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
'''Sample output:''' |
'''Sample output:''' |
||
<pre>'][' problem |
<pre>'][' problem |
||
Line 914: | Line 914: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
< |
<syntaxhighlight lang=ARM_Assembly> |
||
.data |
.data |
||
Line 974: | Line 974: | ||
mov pc, lr |
mov pc, lr |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>isBalanced: function [s][ |
||
cnt: 0 |
cnt: 0 |
||
Line 1,000: | Line 1,000: | ||
if? isBalanced str -> print " OK" |
if? isBalanced str -> print " OK" |
||
else -> print " Not OK" |
else -> print " Not OK" |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,016: | Line 1,016: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang=AutoHotkey>; Generate 10 strings with equal left and right brackets |
||
Loop, 5 |
Loop, 5 |
||
{ |
{ |
||
Line 1,047: | Line 1,047: | ||
} |
} |
||
Return "OK" |
Return "OK" |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,063: | Line 1,063: | ||
A second example repeatedly replacing []: |
A second example repeatedly replacing []: |
||
< |
<syntaxhighlight lang=AutoHotkey>Loop, 5 |
||
{ |
{ |
||
B = %A_Index% |
B = %A_Index% |
||
Line 1,085: | Line 1,085: | ||
StringReplace, Str, Str,[],,All |
StringReplace, Str, Str,[],,All |
||
Return Str ? "False" : "True" |
Return Str ? "False" : "True" |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 1,101: | Line 1,101: | ||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
< |
<syntaxhighlight lang=AutoIt> |
||
#include <Array.au3> |
#include <Array.au3> |
||
Local $Array[1] |
Local $Array[1] |
||
Line 1,130: | Line 1,130: | ||
Return 1 |
Return 1 |
||
EndFunc |
EndFunc |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang=AWK>#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
print isbb("[]") |
print isbb("[]") |
||
Line 1,155: | Line 1,155: | ||
return (s==0) |
return (s==0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre>1 |
<pre>1 |
||
Line 1,165: | Line 1,165: | ||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
< |
<syntaxhighlight lang=bacon>FOR len = 0 TO 18 STEP 2 |
||
str$ = "" |
str$ = "" |
||
Line 1,187: | Line 1,187: | ||
PRINT "BAD: ", str$ |
PRINT "BAD: ", str$ |
||
ENDIF |
ENDIF |
||
NEXT</ |
NEXT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>OK: |
<pre>OK: |
||
Line 1,203: | Line 1,203: | ||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
< |
<syntaxhighlight lang=qbasic>DECLARE FUNCTION checkBrackets% (brackets AS STRING) |
||
DECLARE FUNCTION generator$ (length AS INTEGER) |
DECLARE FUNCTION generator$ (length AS INTEGER) |
||
Line 1,259: | Line 1,259: | ||
NEXT |
NEXT |
||
generator$ = xx$ |
generator$ = xx$ |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 1,277: | Line 1,277: | ||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
Based on ZX Spectrum BASIC implementation |
Based on ZX Spectrum BASIC implementation |
||
< |
<syntaxhighlight lang=basic>10 PRINT CHR$(147): REM CLEAR SCREEN |
||
20 FOR N=1 TO 7 |
20 FOR N=1 TO 7 |
||
30 READ S$ |
30 READ S$ |
||
Line 1,297: | Line 1,297: | ||
1090 PRINT "NOT OK" |
1090 PRINT "NOT OK" |
||
1100 RETURN |
1100 RETURN |
||
2000 DATA , [], ][, [][], ][][, [[][]], []][[]</ |
2000 DATA , [], ][, [][], ][][, [[][]], []][[]</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|Yabasic}} |
{{trans|Yabasic}} |
||
< |
<syntaxhighlight lang=BASIC256>s$ = "[[]][]" |
||
print s$; " = "; |
print s$; " = "; |
||
Line 1,322: | Line 1,322: | ||
next i |
next i |
||
return level = 0 |
return level = 0 |
||
end function</ |
end function</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Uses the rewrite rule <code>"[]" -> null</code> to check if brackets are balanced. |
Uses the rewrite rule <code>"[]" -> null</code> to check if brackets are balanced. |
||
< |
<syntaxhighlight lang=dos>:: Balanced Brackets Task from Rosetta Code |
||
:: Batch File Implementation |
:: Batch File Implementation |
||
Line 1,379: | Line 1,379: | ||
set "old=%new%" |
set "old=%new%" |
||
set "new=%old:[]=%" |
set "new=%old:[]=%" |
||
goto check_loop</ |
goto check_loop</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[][][[[[]]][]]]][[][ is NOT Balanced. |
<pre>[][][[[[]]][]]]][[][ is NOT Balanced. |
||
Line 1,404: | Line 1,404: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang=bbcbasic>FOR x%=1 TO 10 |
||
test$=FNgenerate(RND(10)) |
test$=FNgenerate(RND(10)) |
||
PRINT "Bracket string ";test$;" is ";FNvalid(test$) |
PRINT "Bracket string ";test$;" is ";FNvalid(test$) |
||
Line 1,432: | Line 1,432: | ||
IF count%<0 THEN ="not OK." |
IF count%<0 THEN ="not OK." |
||
NEXT x% |
NEXT x% |
||
="OK."</ |
="OK."</syntaxhighlight> |
||
<pre>Bracket string [[[][]]] is OK. |
<pre>Bracket string [[[][]]] is OK. |
||
Bracket string [[[]][[[][[][]]]]] is OK. |
Bracket string [[[]][[[][[][]]]]] is OK. |
||
Line 1,447: | Line 1,447: | ||
{{works with|befungee}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang=Befunge>v > "KO TON" ,,,,,, v |
||
> ~ : 25*- #v_ $ | > 25*, @ |
> ~ : 25*- #v_ $ | > 25*, @ |
||
> "KO" ,, ^ |
> "KO" ,, ^ |
||
Line 1,453: | Line 1,453: | ||
> \ : 1991+*+- #v_v |
> \ : 1991+*+- #v_v |
||
\ $ |
\ $ |
||
^ < <$<</ |
^ < <$<</syntaxhighlight> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 1,462: | Line 1,462: | ||
This allows for a particular simple implementation: |
This allows for a particular simple implementation: |
||
< |
<syntaxhighlight lang=bqn>Gen ← (•rand.Deal⊏⥊⟜"[]") 2⊸× |
||
Bal ← { |
Bal ← { |
||
Mul ← {a‿b𝕊x‿y: ⟨a+0⌈x-b, y+0⌈b-x⟩} |
Mul ← {a‿b𝕊x‿y: ⟨a+0⌈x-b, y+0⌈b-x⟩} |
||
0‿0 ≡ 0‿0("]["⊸=⊸Mul)´𝕩 |
0‿0 ≡ 0‿0("]["⊸=⊸Mul)´𝕩 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,480: | Line 1,480: | ||
=={{header|Bracmat}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang=bracmat>( (bal=|"[" !bal "]" !bal) |
||
& ( generate |
& ( generate |
||
= a j m n z N S someNumber |
= a j m n z N S someNumber |
||
Line 1,506: | Line 1,506: | ||
& !L+1:<11:?L |
& !L+1:<11:?L |
||
) |
) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>:Balanced |
<pre>:Balanced |
||
Line 1,521: | Line 1,521: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang=brat>string.prototype.balanced? = { |
||
brackets = [] |
brackets = [] |
||
balanced = true |
balanced = true |
||
Line 1,551: | Line 1,551: | ||
{ p "#{test} is balanced" } |
{ p "#{test} is balanced" } |
||
{ p "#{test} is not balanced" } |
{ p "#{test} is not balanced" } |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,566: | Line 1,566: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang=c>#include<stdio.h> |
||
#include<stdlib.h> |
#include<stdlib.h> |
||
#include<string.h> |
#include<string.h> |
||
Line 1,608: | Line 1,608: | ||
while(n<9) doSeq(n++); |
while(n<9) doSeq(n++); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight>result:<syntaxhighlight lang=text>'': True |
||
'[]': True |
'[]': True |
||
']][[': False |
']][[': False |
||
Line 1,616: | Line 1,616: | ||
']]]][[[]][[[': False |
']]]][[[]][[[': False |
||
']]]]]][][[[[[[': False |
']]]]]][][[[[[[': False |
||
'[][]][[][[[]]][]': False</ |
'[][]][[][[[]]][]': False</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 1,660: | Line 1,660: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>"" is balanced. |
<pre>"" is balanced. |
||
Line 1,671: | Line 1,671: | ||
"[]]][][]][[][[" is not balanced. |
"[]]][][]][[][[" is not balanced. |
||
"[]]][]]][[][[][[" is not balanced.</pre> |
"[]]][]]][[][[][[" is not balanced.</pre> |
||
< |
<syntaxhighlight lang=csharp> |
||
// simple solution |
// simple solution |
||
string input = Console.ReadLine(); |
string input = Console.ReadLine(); |
||
Line 1,696: | Line 1,696: | ||
Console.WriteLine("Not Okay"); |
Console.WriteLine("Not Okay"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang=cpp>#include <algorithm> |
||
#include <iostream> |
#include <iostream> |
||
#include <string> |
#include <string> |
||
Line 1,731: | Line 1,731: | ||
std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n"; |
std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n"; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> ok: |
<pre> ok: |
||
Line 1,745: | Line 1,745: | ||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang=Ceylon>import com.vasileff.ceylon.random.api { |
||
platformRandom, |
platformRandom, |
||
Random |
Random |
||
Line 1,771: | Line 1,771: | ||
ints.filter((i) => i != 0) |
ints.filter((i) => i != 0) |
||
.scan(0)(plus<Integer>) |
.scan(0)(plus<Integer>) |
||
.every((i) => i >= 0);</ |
.every((i) => i >= 0);</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,788: | Line 1,788: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang=Clojure>(defn gen-brackets [n] |
||
(->> (concat (repeat n \[) (repeat n \])) |
(->> (concat (repeat n \[) (repeat n \])) |
||
shuffle |
shuffle |
||
Line 1,801: | Line 1,801: | ||
(when (= (peek stack) \[) |
(when (= (peek stack) \[) |
||
(recur coll (pop stack)))) |
(recur coll (pop stack)))) |
||
(zero? (count stack)))))</ |
(zero? (count stack)))))</syntaxhighlight> |
||
There are other ways to express the <code>balanced?</code> function. |
There are other ways to express the <code>balanced?</code> function. |
||
* We can use <code>reduce</code> to consume the sequence: |
* We can use <code>reduce</code> to consume the sequence: |
||
:< |
:<syntaxhighlight lang=Clojure>(defn balanced? [s] |
||
(empty? |
(empty? |
||
(reduce |
(reduce |
||
Line 1,816: | Line 1,816: | ||
(reduced [:UNDERFLOW])))) |
(reduced [:UNDERFLOW])))) |
||
'() |
'() |
||
s)))</ |
s)))</syntaxhighlight> |
||
* Only <code>[</code>s are put on the stack. We can just count the unmatched ones. |
* Only <code>[</code>s are put on the stack. We can just count the unmatched ones. |
||
:< |
:<syntaxhighlight lang=Clojure>(defn balanced? [s] |
||
(let [opens-closes (->> s |
(let [opens-closes (->> s |
||
(map {\[ 1, \] -1}) |
(map {\[ 1, \] -1}) |
||
(reductions + 0))] |
(reductions + 0))] |
||
(and (not-any? neg? opens-closes) (zero? (last opens-closes))))) </ |
(and (not-any? neg? opens-closes) (zero? (last opens-closes))))) </syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,843: | Line 1,843: | ||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang=clu>% This program needs the random number generator from |
||
% "misc.lib" that comes with PCLU. |
% "misc.lib" that comes with PCLU. |
||
Line 1,893: | Line 1,893: | ||
end |
end |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"": balanced |
<pre>"": balanced |
||
Line 1,909: | Line 1,909: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. test-balanced-brackets. |
PROGRAM-ID. test-balanced-brackets. |
||
Line 2,006: | Line 2,006: | ||
. |
. |
||
END PROGRAM check-if-balanced.</ |
END PROGRAM check-if-balanced.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang=coffeescript> |
||
isBalanced = (brackets) -> |
isBalanced = (brackets) -> |
||
openCount = 0 |
openCount = 0 |
||
Line 2,025: | Line 2,025: | ||
for brackets in bracketsCombinations 4 |
for brackets in bracketsCombinations 4 |
||
console.log brackets, isBalanced brackets |
console.log brackets, isBalanced brackets |
||
</syntaxhighlight> |
|||
</lang> |
|||
output |
output |
||
<lang> |
<syntaxhighlight lang=text> |
||
> coffee balanced.coffee |
> coffee balanced.coffee |
||
[[[[ false |
[[[[ false |
||
Line 2,045: | Line 2,045: | ||
]]][ false |
]]][ false |
||
]]]] false |
]]]] false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp> |
||
(defun string-of-brackets (n) |
(defun string-of-brackets (n) |
||
(let* ((len (* 2 n)) |
(let* ((len (* 2 n)) |
||
Line 2,076: | Line 2,076: | ||
(let ((s (string-of-brackets i))) |
(let ((s (string-of-brackets i))) |
||
(format t "~3A: ~A~%" (balancedp s) s)))) |
(format t "~3A: ~A~%" (balancedp s) s)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 2,096: | Line 2,096: | ||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Brackets; |
MODULE Brackets; |
||
IMPORT StdLog, Args, Stacks (* See Task Stacks *); |
IMPORT StdLog, Args, Stacks (* See Task Stacks *); |
||
Line 2,157: | Line 2,157: | ||
END Brackets. |
END Brackets. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q Brackets.Do [] [][] [[][]] ][ ][][ []][[]~<br/> |
Execute: ^Q Brackets.Do [] [][] [[][]] ][ ][][ []][[]~<br/> |
||
Output: |
Output: |
||
Line 2,170: | Line 2,170: | ||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang=ruby>def generate(n : Int) |
||
(['[',']'] * n).shuffle.join # Implicit return |
(['[',']'] * n).shuffle.join # Implicit return |
||
end |
end |
||
Line 2,195: | Line 2,195: | ||
str = generate(i) |
str = generate(i) |
||
puts "#{str}: #{is_balanced(str)}" |
puts "#{str}: #{is_balanced(str)}" |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,213: | Line 2,213: | ||
===Standard Version=== |
===Standard Version=== |
||
D standard library has a [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html#balancedParens function] for this. |
D standard library has a [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html#balancedParens function] for this. |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.random, std.range; |
||
void main() { |
void main() { |
||
Line 2,220: | Line 2,220: | ||
writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s); |
writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> OK: [] |
<pre> OK: [] |
||
Line 2,233: | Line 2,233: | ||
===Imperative Version=== |
===Imperative Version=== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.random, std.range, std.algorithm; |
||
bool isBalanced(in string txt) pure nothrow { |
bool isBalanced(in string txt) pure nothrow { |
||
Line 2,255: | Line 2,255: | ||
writeln(s.isBalanced ? " OK " : "Bad ", s); |
writeln(s.isBalanced ? " OK " : "Bad ", s); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
The output is similar. |
The output is similar. |
||
===Functional Style=== |
===Functional Style=== |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.random, std.range, std.algorithm; |
||
bool isBalanced(in string s, in char[2] pars="[]") pure nothrow @safe @nogc { |
bool isBalanced(in string s, in char[2] pars="[]") pure nothrow @safe @nogc { |
||
Line 2,278: | Line 2,278: | ||
writeln(s.isBalanced ? " OK " : "Bad ", s); |
writeln(s.isBalanced ? " OK " : "Bad ", s); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang=Delphi>procedure Balanced_Brackets; |
||
var BracketsStr : string; |
var BracketsStr : string; |
||
Line 2,312: | Line 2,312: | ||
writeln(BracketsStr+': not OK'); |
writeln(BracketsStr+': not OK'); |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 2,327: | Line 2,327: | ||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang=dejavu>matching?: |
||
swap 0 |
swap 0 |
||
for c in chars: |
for c in chars: |
||
Line 2,345: | Line 2,345: | ||
!. matching? "][" |
!. matching? "][" |
||
!. matching? "][][" |
!. matching? "][][" |
||
!. matching? "[]][[]"</ |
!. matching? "[]][[]"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>true |
<pre>true |
||
Line 2,356: | Line 2,356: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang=scheme> |
||
(define (balance str) |
(define (balance str) |
||
(for/fold (closed 0) ((par str)) |
(for/fold (closed 0) ((par str)) |
||
Line 2,385: | Line 2,385: | ||
❌ "[[][]]][" |
❌ "[[][]]][" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang=elena>import system'routines; |
||
import extensions; |
import extensions; |
||
import extensions'text; |
import extensions'text; |
||
Line 2,434: | Line 2,434: | ||
console.readChar() |
console.readChar() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,452: | Line 2,452: | ||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
{{works with|Elixir|1.1}} |
{{works with|Elixir|1.1}} |
||
< |
<syntaxhighlight lang=elixir>defmodule Balanced_brackets do |
||
def task do |
def task do |
||
Enum.each(0..5, fn n -> |
Enum.each(0..5, fn n -> |
||
Line 2,478: | Line 2,478: | ||
end |
end |
||
Balanced_brackets.task</ |
Balanced_brackets.task</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,491: | Line 2,491: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang=Erlang> |
||
-module( balanced_brackets ). |
-module( balanced_brackets ). |
||
-export( [generate/1, is_balanced/1, task/0] ). |
-export( [generate/1, is_balanced/1, task/0] ). |
||
Line 2,521: | Line 2,521: | ||
task_balanced( true ) -> "OK"; |
task_balanced( true ) -> "OK"; |
||
task_balanced( false ) -> "NOT OK". |
task_balanced( false ) -> "NOT OK". |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,534: | Line 2,534: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang=euphoria>function check_brackets(sequence s) |
||
integer level |
integer level |
||
level = 0 |
level = 0 |
||
Line 2,578: | Line 2,578: | ||
puts(1," NOT OK\n") |
puts(1," NOT OK\n") |
||
end if |
end if |
||
end for</ |
end for</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 2,600: | Line 2,600: | ||
{{Works with|Office 365 betas 2021}} |
{{Works with|Office 365 betas 2021}} |
||
< |
<syntaxhighlight lang=lisp>bracketReport |
||
=LAMBDA(bracketPair, |
=LAMBDA(bracketPair, |
||
LAMBDA(s, |
LAMBDA(s, |
||
Line 2,685: | Line 2,685: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
and also assuming the following generic bindings in the Name Manager for the WorkBook: |
and also assuming the following generic bindings in the Name Manager for the WorkBook: |
||
< |
<syntaxhighlight lang=lisp>APPENDCOLS |
||
=LAMBDA(xs, |
=LAMBDA(xs, |
||
LAMBDA(ys, |
LAMBDA(ys, |
||
Line 2,798: | Line 2,798: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,913: | Line 2,913: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang=fsharp>let isBalanced str = |
||
let rec loop count = function |
let rec loop count = function |
||
| ']'::_ when count = 0 -> false |
| ']'::_ when count = 0 -> false |
||
Line 2,934: | Line 2,934: | ||
for n in 1..10 do |
for n in 1..10 do |
||
let s = generate n |
let s = generate n |
||
printfn "\"%s\" is balanced: %b" s (isBalanced s)</ |
printfn "\"%s\" is balanced: %b" s (isBalanced s)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,950: | Line 2,950: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
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. |
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. |
||
< |
<syntaxhighlight lang=Factor>USING: io formatting locals kernel math sequences unicode.case ; |
||
IN: balanced-brackets |
IN: balanced-brackets |
||
Line 2,971: | Line 2,971: | ||
readln |
readln |
||
balanced</ |
balanced</syntaxhighlight> |
||
Some more idiomatic solution might be as follows: |
Some more idiomatic solution might be as follows: |
||
< |
<syntaxhighlight lang=Factor>USING: io formatting locals kernel math sequences unicode.case ; |
||
IN: balanced-brackets |
IN: balanced-brackets |
||
Line 2,995: | Line 2,995: | ||
-- Data stack: |
-- Data stack: |
||
t |
t |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang=fantom> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 3,039: | Line 3,039: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output (for n=3): |
Output (for n=3): |
||
Line 3,067: | Line 3,067: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
{{works with|4tH|3.61.1}} |
{{works with|4tH|3.61.1}} |
||
< |
<syntaxhighlight lang=forth>include lib/choose.4th ( n1 -- n2) |
||
include lib/ctos.4th ( n -- a 1) |
include lib/ctos.4th ( n -- a 1) |
||
Line 3,089: | Line 3,089: | ||
; \ evaluate string and print result |
; \ evaluate string and print result |
||
make[] eval[]</ |
make[] eval[]</syntaxhighlight> |
||
'''Examples''':<pre>[][[]] OK |
'''Examples''':<pre>[][[]] OK |
||
[[[[]][[ NOT OK |
[[[[]][[ NOT OK |
||
Line 3,105: | Line 3,105: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Please see the compilation and program execution result as comments at the top of this source: |
Please see the compilation and program execution result as comments at the top of this source: |
||
< |
<syntaxhighlight lang=fortran> |
||
! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe |
! $ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe |
||
! $ ./f |
! $ ./f |
||
Line 3,203: | Line 3,203: | ||
end subroutine generate |
end subroutine generate |
||
end program balanced_brackets |
end program balanced_brackets |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64 |
||
Function isBalanced(s As String) As Boolean |
Function isBalanced(s As String) As Boolean |
||
Line 3,250: | Line 3,250: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
Sample output (last 7 lines random) : |
Sample output (last 7 lines random) : |
||
{{out}} |
{{out}} |
||
Line 3,272: | Line 3,272: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=8960fb267af43f0549d2cfe04288a2d4 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=8960fb267af43f0549d2cfe04288a2d4 Click this link to run this code]''' |
||
< |
<syntaxhighlight 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 |
siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line |
||
Line 3,344: | Line 3,344: | ||
Return sBrk 'Return the sBrk array |
Return sBrk 'Return the sBrk array |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,366: | Line 3,366: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap>Balanced := function(L) |
||
local c, r; |
local c, r; |
||
r := 0; |
r := 0; |
||
Line 3,401: | Line 3,401: | ||
Balanced("[[[]][]]]"); |
Balanced("[[[]][]]]"); |
||
# false</ |
# false</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang=go>package main |
||
import ( |
import ( |
||
Line 3,457: | Line 3,457: | ||
} |
} |
||
testBalanced("()") |
testBalanced("()") |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,475: | Line 3,475: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Generate Arbitrary String of Bracket Pairs: |
Generate Arbitrary String of Bracket Pairs: |
||
< |
<syntaxhighlight lang=groovy>def random = new Random() |
||
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 } |
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 } |
||
Line 3,495: | Line 3,495: | ||
def p = random.nextInt(factorial(n*2)) |
def p = random.nextInt(factorial(n*2)) |
||
makePermutation(base, p) |
makePermutation(base, p) |
||
}</ |
}</syntaxhighlight> |
||
Check Balance of Bracket String: |
Check Balance of Bracket String: |
||
< |
<syntaxhighlight lang=groovy>boolean balancedBrackets(String brackets, int depth=0) { |
||
if (brackets == null || brackets.empty) return depth == 0 |
if (brackets == null || brackets.empty) return depth == 0 |
||
switch (brackets[0]) { |
switch (brackets[0]) { |
||
Line 3,508: | Line 3,508: | ||
return brackets.size() == 1 ? depth == 0 : balancedBrackets(brackets[1..-1], depth) |
return brackets.size() == 1 ? depth == 0 : balancedBrackets(brackets[1..-1], depth) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang=groovy>Set brackets = [] |
||
(0..100).each { |
(0..100).each { |
||
(0..8).each { r -> |
(0..8).each { r -> |
||
Line 3,523: | Line 3,523: | ||
def bal = balancedBrackets(it) ? "balanced: " : "unbalanced: " |
def bal = balancedBrackets(it) ? "balanced: " : "unbalanced: " |
||
println "${bal} ${it}" |
println "${bal} ${it}" |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,722: | Line 3,722: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
The simplest solution exploits the idea of stack-based automaton, which could be implemented by a fold. |
The simplest solution exploits the idea of stack-based automaton, which could be implemented by a fold. |
||
< |
<syntaxhighlight lang=haskell> |
||
isMatching :: String -> Bool |
isMatching :: String -> Bool |
||
isMatching = null . foldl aut [] |
isMatching = null . foldl aut [] |
||
Line 3,729: | Line 3,729: | ||
-- aut ('{':s) '}' = s -- automaton could be extended |
-- aut ('{':s) '}' = s -- automaton could be extended |
||
aut s x = x:s |
aut s x = x:s |
||
</syntaxhighlight> |
|||
</lang> |
|||
This generates an infinite stream of correct balanced brackets expressions: |
This generates an infinite stream of correct balanced brackets expressions: |
||
< |
<syntaxhighlight lang=haskell>brackets = filter isMatching |
||
$ [1.. ] >>= (`replicateM` "[]{}") </ |
$ [1.. ] >>= (`replicateM` "[]{}") </syntaxhighlight> |
||
<pre>λ> take 10 brackets |
<pre>λ> take 10 brackets |
||
["[]","{}","[[]]","[][]","[]{}","[{}]","{[]}","{{}}","{}[]","{}{}"]</pre> |
["[]","{}","[[]]","[][]","[]{}","[{}]","{[]}","{{}}","{}[]","{}{}"]</pre> |
||
Line 3,740: | Line 3,740: | ||
In case the index of unmatched opening bracket is need to be found, following solution is suitable. |
In case the index of unmatched opening bracket is need to be found, following solution is suitable. |
||
< |
<syntaxhighlight lang=haskell> |
||
import Control.Monad |
import Control.Monad |
||
import System.Random |
import System.Random |
||
Line 3,771: | Line 3,771: | ||
let bs = cycle "[]" |
let bs = cycle "[]" |
||
rs <- replicateM 10 newStdGen |
rs <- replicateM 10 newStdGen |
||
zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2 ..] rs</ |
zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2 ..] rs</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang=haskell>module VShuffle |
||
( shuffle |
( shuffle |
||
) where |
) where |
||
Line 3,802: | Line 3,802: | ||
do v <- V.unsafeThaw $ V.fromList xs |
do v <- V.unsafeThaw $ V.fromList xs |
||
mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r |
mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r |
||
V.unsafeFreeze v</ |
V.unsafeFreeze v</syntaxhighlight> |
||
Here's some sample output. |
Here's some sample output. |
||
<pre> |
<pre> |
||
Line 3,827: | Line 3,827: | ||
and '''scanl''' also yields a simple fit when we want the index of the tipping point: |
and '''scanl''' also yields a simple fit when we want the index of the tipping point: |
||
< |
<syntaxhighlight lang=haskell>import Control.Applicative ((<|>)) |
||
import Data.List (findIndex, replicate, scanl) |
import Data.List (findIndex, replicate, scanl) |
||
import Data.List.Split (chunksOf) |
import Data.List.Split (chunksOf) |
||
Line 3,866: | Line 3,866: | ||
bracket :: Int -> Char |
bracket :: Int -> Char |
||
bracket 0 = '[' |
bracket 0 = '[' |
||
bracket _ = ']'</ |
bracket _ = ']'</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>]][]][: Unmatched |
<pre>]][]][: Unmatched |
||
Line 3,891: | Line 3,891: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang=Icon>procedure main(arglist) |
||
every s := genbs(!arglist) do |
every s := genbs(!arglist) do |
||
write(image(s), if isbalanced(s) then " is balanced." else " is unbalanced") |
write(image(s), if isbalanced(s) then " is balanced." else " is unbalanced") |
||
Line 3,905: | Line 3,905: | ||
every !s := ?s # shuffle |
every !s := ?s # shuffle |
||
return s |
return s |
||
end</ |
end</syntaxhighlight> |
||
Output:<pre> |
Output:<pre> |
||
Line 3,923: | Line 3,923: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''': < |
'''Solution''': <syntaxhighlight lang=j>bracketDepth =: '[]' -&(+/\)/@:(=/) ] |
||
checkBalanced =: _1 -.@e. bracketDepth |
checkBalanced =: _1 -.@e. bracketDepth |
||
genBracketPairs =: (?~@# { ])@#"0 1&'[]' NB. bracket pairs in arbitrary order</ |
genBracketPairs =: (?~@# { ])@#"0 1&'[]' NB. bracket pairs in arbitrary order</syntaxhighlight> |
||
'''Examples''':< |
'''Examples''':<syntaxhighlight lang=j> (, ' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10 |
||
OK |
OK |
||
][ bad |
][ bad |
||
Line 3,936: | Line 3,936: | ||
[[]][[][][]][] OK |
[[]][[][][]][] OK |
||
]]]][[][][[[[]][ bad |
]]]][[][][[[[]][ bad |
||
[]]][][][[[[]][[]] bad</ |
[]]][][][[[[]][[]] bad</syntaxhighlight> |
||
'''Comments''': This task highlights the versatility and usefulness of J's scanning modifiers, <code>/</code> and <code>\</code>. |
'''Comments''': This task highlights the versatility and usefulness of J's scanning modifiers, <code>/</code> and <code>\</code>. |
||
Line 3,943: | Line 3,943: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang=java5>public class BalancedBrackets { |
||
public static boolean hasBalancedBrackets(String str) { |
public static boolean hasBalancedBrackets(String str) { |
||
Line 3,991: | Line 3,991: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample output (generate uses random numbers, so it should not be the same every time): |
Sample output (generate uses random numbers, so it should not be the same every time): |
||
<pre>: true |
<pre>: true |
||
Line 4,011: | Line 4,011: | ||
=== Extended === |
=== Extended === |
||
< |
<syntaxhighlight lang=java>import java.util.ArrayDeque; |
||
import java.util.Deque; |
import java.util.Deque; |
||
Line 4,074: | Line 4,074: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>With areSquareBracketsBalanced: |
<pre>With areSquareBracketsBalanced: |
||
Line 4,101: | Line 4,101: | ||
====Iterative==== |
====Iterative==== |
||
< |
<syntaxhighlight lang=JavaScript>function shuffle(str) { |
||
var a = str.split(''), b, c = a.length, d |
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 |
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d |
||
Line 4,117: | Line 4,117: | ||
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N)) |
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N)) |
||
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced') |
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced') |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 4,144: | Line 4,144: | ||
==== Another solution ==== |
==== Another solution ==== |
||
{{works with|Node.js}} |
{{works with|Node.js}} |
||
< |
<syntaxhighlight lang=JavaScript> |
||
console.log("Supplied examples"); |
console.log("Supplied examples"); |
||
var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]; |
var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]; |
||
Line 4,201: | Line 4,201: | ||
return generated; |
return generated; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,229: | Line 4,229: | ||
====Functional==== |
====Functional==== |
||
With visual indication of where the balance fails: |
With visual indication of where the balance fails: |
||
< |
<syntaxhighlight lang=JavaScript>(() => { |
||
'use strict'; |
'use strict'; |
||
Line 4,333: | Line 4,333: | ||
// --- |
// --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>'' OK |
<pre>'' OK |
||
Line 4,348: | Line 4,348: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang=julia>using Printf |
||
function balancedbrackets(str::AbstractString) |
function balancedbrackets(str::AbstractString) |
||
Line 4,363: | Line 4,363: | ||
for (test, pass) in map(x -> (x, balancedbrackets(x)), collect(brackets(i) for i = 0:8)) |
for (test, pass) in map(x -> (x, balancedbrackets(x)), collect(brackets(i) for i = 0:8)) |
||
@printf("%22s%10s\n", test, pass ? "pass" : "fail") |
@printf("%22s%10s\n", test, pass ? "pass" : "fail") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,377: | Line 4,377: | ||
'''One-line version''': |
'''One-line version''': |
||
< |
<syntaxhighlight lang=julia>balancedbrackets(str::AbstractString) = foldl((x, y) -> x < 0 ? -1 : x + y, collect((x == '[') - (x == ']') for x in str), init = 0) == 0</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang=K> |
|||
<lang K> |
|||
gen_brackets:{"[]"@x _draw 2} |
gen_brackets:{"[]"@x _draw 2} |
||
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)} |
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)} |
||
Line 4,395: | Line 4,395: | ||
("][[][[]]][[]]]][][";0) |
("][[][[]]][[]]]][][";0) |
||
("]][[[[]]]][][][[]]]]";0)) |
("]][[[[]]]][][][[]]]]";0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
<lang>"[[]][]]" |
<syntaxhighlight lang=text>"[[]][]]" |
||
%acc 0 !acc |
%acc 0 !acc |
||
Line 4,415: | Line 4,415: | ||
print |
print |
||
" " input</ |
" " input</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang=scala>import java.util.Random |
||
fun isBalanced(s: String): Boolean { |
fun isBalanced(s: String): Boolean { |
||
Line 4,450: | Line 4,450: | ||
println("$s " + if (isBalanced(s)) "OK" else "NOT OK") |
println("$s " + if (isBalanced(s)) "OK" else "NOT OK") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample output (last 7 lines random) : |
Sample output (last 7 lines random) : |
||
{{out}} |
{{out}} |
||
Line 4,474: | Line 4,474: | ||
=={{header|L++}}== |
=={{header|L++}}== |
||
< |
<syntaxhighlight lang=lisp>(include "string") |
||
(defn bool balanced (std::string s) |
(defn bool balanced (std::string s) |
||
Line 4,488: | Line 4,488: | ||
(pr std::boolalpha) |
(pr std::boolalpha) |
||
(foreach x tests |
(foreach x tests |
||
(prn x "\t" (balanced x))))</ |
(prn x "\t" (balanced x))))</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang=Lasso>define randomparens(num::integer,open::string='[',close::string=']') => { |
||
local(out) = array |
local(out) = array |
||
Line 4,512: | Line 4,512: | ||
with i in 1 to 10 |
with i in 1 to 10 |
||
let input = randomparens(#i) |
let input = randomparens(#i) |
||
select #input + ' = ' + validateparens(#input)</ |
select #input + ' = ' + validateparens(#input)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,526: | Line 4,526: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
print "Supplied examples" |
print "Supplied examples" |
||
for i =1 to 7 |
for i =1 to 7 |
||
Line 4,589: | Line 4,589: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Supplied examples |
Supplied examples |
||
The string '' is OK. |
The string '' is OK. |
||
Line 4,612: | Line 4,612: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang=Lua> |
||
function isBalanced(s) |
function isBalanced(s) |
||
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters. |
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters. |
||
Line 4,633: | Line 4,633: | ||
print(RS) |
print(RS) |
||
print(isBalanced(RS)) |
print(isBalanced(RS)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
This functionality is provided by Maple. |
This functionality is provided by Maple. |
||
< |
<syntaxhighlight lang=Maple> |
||
> use StringTools in |
> use StringTools in |
||
> IsBalanced( "", "[", "]" ); |
> IsBalanced( "", "[", "]" ); |
||
Line 4,669: | Line 4,669: | ||
false |
false |
||
</syntaxhighlight> |
|||
</lang> |
|||
Furthermore, Maple can check whether multiple fences are balanced in the same string. |
Furthermore, Maple can check whether multiple fences are balanced in the same string. |
||
< |
<syntaxhighlight lang=Maple> |
||
> StringTools:-IsBalanced( "[()()]", "[(", "])" ); |
> StringTools:-IsBalanced( "[()()]", "[(", "])" ); |
||
true |
true |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang=mathematica>(* Generate open/close events. *) |
||
gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten] |
gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten] |
||
Line 4,689: | Line 4,689: | ||
Print[str <> If[match[lst, 0], |
Print[str <> If[match[lst, 0], |
||
" is balanced.", |
" is balanced.", |
||
" is not balanced."]])</ |
" is not balanced."]])</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang=matlab>function x = isbb(s) |
||
t = cumsum((s=='[') - (s==']')); |
t = cumsum((s=='[') - (s==']')); |
||
x = all(t>=0) && (t(end)==0); |
x = all(t>=0) && (t(end)==0); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,715: | Line 4,715: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang=maxima>brack(s) := block( |
||
[n: slength(s), r: 0, c], |
[n: slength(s), r: 0, c], |
||
catch( |
catch( |
||
Line 4,745: | Line 4,745: | ||
brack("[[[]][]]]"); |
brack("[[[]][]]]"); |
||
false</ |
false</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang=Mercury> |
||
:- module balancedbrackets. |
:- module balancedbrackets. |
||
:- interface. |
:- interface. |
||
Line 4,789: | Line 4,789: | ||
; print(" is unbalanced\n", !IO) |
; print(" is unbalanced\n", !IO) |
||
). |
). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
Line 4,795: | Line 4,795: | ||
We start by defining a function: |
We start by defining a function: |
||
< |
<syntaxhighlight lang=MiniScript>isBalanced = function(str) |
||
level = 0 |
level = 0 |
||
for c in str |
for c in str |
||
Line 4,803: | Line 4,803: | ||
end for |
end for |
||
return level == 0 |
return level == 0 |
||
end function</ |
end function</syntaxhighlight> |
||
We can evaluate the example strings with this code: |
We can evaluate the example strings with this code: |
||
< |
<syntaxhighlight lang=MiniScript>examples = [ |
||
"", |
"", |
||
"[]", |
"[]", |
||
Line 4,821: | Line 4,821: | ||
if balanced then outcome = "is OK" else outcome = "NOT OK" |
if balanced then outcome = "is OK" else outcome = "NOT OK" |
||
print """" + str + """ " + outcome |
print """" + str + """ " + outcome |
||
end for</ |
end for</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,836: | Line 4,836: | ||
{{works with|TopSpeed (JPI) Modula-2 under DOSBox-X}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang=modula2> |
||
MODULE Brackets; |
MODULE Brackets; |
||
IMPORT IO, Lib; |
IMPORT IO, Lib; |
||
Line 4,884: | Line 4,884: | ||
END; |
END; |
||
END Brackets. |
END Brackets. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,901: | Line 4,901: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=Nanoquery>import Nanoquery.Util |
||
def gen(N) |
def gen(N) |
||
Line 4,933: | Line 4,933: | ||
println format("%-22s is not balanced", txt) |
println format("%-22s is not balanced", txt) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> is balanced |
<pre> is balanced |
||
Line 4,948: | Line 4,948: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=nim> |
||
from random import random, randomize, shuffle |
from random import random, randomize, shuffle |
||
from strutils import repeat |
from strutils import repeat |
||
Line 4,972: | Line 4,972: | ||
for n in 0..9: |
for n in 0..9: |
||
let s = gen(n) |
let s = gen(n) |
||
echo "'", s, "' is ", (if balanced(s): "balanced" else: "not balanced")</ |
echo "'", s, "' is ", (if balanced(s): "balanced" else: "not balanced")</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>'' is balanced |
<pre>'' is balanced |
||
Line 4,987: | Line 4,987: | ||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{works with|oo2c version 2}} |
{{works with|oo2c version 2}} |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE BalancedBrackets; |
MODULE BalancedBrackets; |
||
IMPORT |
IMPORT |
||
Line 5,090: | Line 5,090: | ||
Do |
Do |
||
END BalancedBrackets. |
END BalancedBrackets. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,102: | Line 5,102: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang=objeck> |
||
bundle Default { |
bundle Default { |
||
class Balanced { |
class Balanced { |
||
Line 5,135: | Line 5,135: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
: true |
: true |
||
Line 5,148: | Line 5,148: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang=ocaml>let generate_brackets n = |
||
let rec aux i acc = |
let rec aux i acc = |
||
if i <= 0 then acc else |
if i <= 0 then acc else |
||
Line 5,172: | Line 5,172: | ||
List.iter print_char brk; |
List.iter print_char brk; |
||
Printf.printf " %B\n" (is_balanced brk); |
Printf.printf " %B\n" (is_balanced brk); |
||
;;</ |
;;</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 5,183: | Line 5,183: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang=Oforth>String method: isBalanced |
||
| c | |
| c | |
||
0 self forEach: c [ |
0 self forEach: c [ |
||
Line 5,193: | Line 5,193: | ||
: genBrackets(n) |
: genBrackets(n) |
||
"" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ;</ |
"" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,211: | Line 5,211: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<syntaxhighlight lang=ooRexx> |
||
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]") |
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]") |
||
Line 5,259: | Line 5,259: | ||
end |
end |
||
return answer~string |
return answer~string |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output (uses randomly generated groupings, so it should be different on each run): |
Sample output (uses randomly generated groupings, so it should be different on each run): |
||
<pre> |
<pre> |
||
Line 5,280: | Line 5,280: | ||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang=oxygenbasic>function CheckBrackets(string s) as bool |
||
'======================================= |
'======================================= |
||
sys co, le=len s |
sys co, le=len s |
||
Line 5,307: | Line 5,307: | ||
print CheckBrackets "[][]"'1 |
print CheckBrackets "[][]"'1 |
||
print CheckBrackets "][" '0 |
print CheckBrackets "][" '0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang=parigp>balanced(s)={ |
||
my(n=0,v=Vecsmall(s)); |
my(n=0,v=Vecsmall(s)); |
||
for(i=1,#v, |
for(i=1,#v, |
||
Line 5,322: | Line 5,322: | ||
}; |
}; |
||
rnd(n)=Strchr(vectorsmall(n,i,if(random(2),91,93))) |
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")))</ |
forstep(n=0,10,2,s=rnd(n);print(s"\t"if(balanced(s),"true","false")))</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 5,331: | Line 5,331: | ||
Idiomatic solution, using a regex that performs subpattern recursion ''(works with Perl 5.10 and newer)'': |
Idiomatic solution, using a regex that performs subpattern recursion ''(works with Perl 5.10 and newer)'': |
||
< |
<syntaxhighlight lang=Perl>sub generate { |
||
my $n = shift; |
my $n = shift; |
||
my $str = '[' x $n; |
my $str = '[' x $n; |
||
Line 5,345: | Line 5,345: | ||
my $input = generate($_); |
my $input = generate($_); |
||
print balanced($input) ? " ok:" : "bad:", " '$input'\n"; |
print balanced($input) ? " ok:" : "bad:", " '$input'\n"; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,362: | Line 5,362: | ||
If input strings are allowed to contain unrelated characters, this can be extended to: |
If input strings are allowed to contain unrelated characters, this can be extended to: |
||
< |
<syntaxhighlight lang=Perl>sub balanced { |
||
shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x; |
shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x; |
||
}</ |
}</syntaxhighlight> |
||
<code>Regexp::Common::balanced</code> can give such a regexp too (non-bracket chars allowed). Its recent versions use the subpattern recursion and are hence also only for Perl 5.10 and up. |
<code>Regexp::Common::balanced</code> can give such a regexp too (non-bracket chars allowed). Its recent versions use the subpattern recursion and are hence also only for Perl 5.10 and up. |
||
< |
<syntaxhighlight lang=Perl>use Regexp::Common 'balanced'; |
||
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/; |
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/; |
||
sub balanced { |
sub balanced { |
||
return shift =~ $re; |
return shift =~ $re; |
||
}</ |
}</syntaxhighlight> |
||
Alternative implementation, using straightforward depth counting: |
Alternative implementation, using straightforward depth counting: |
||
< |
<syntaxhighlight lang=Perl>sub balanced { |
||
my $depth = 0; |
my $depth = 0; |
||
for (split //, shift) { |
for (split //, shift) { |
||
Line 5,383: | Line 5,383: | ||
} |
} |
||
return !$depth |
return !$depth |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<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> |
<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> |
||
Line 5,409: | Line 5,409: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<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}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,435: | Line 5,435: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>"[[]][]" |
||
0 var acc |
0 var acc |
||
Line 5,451: | Line 5,451: | ||
" is OK" |
" is OK" |
||
endif |
endif |
||
print</ |
print</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
The sample is given as unix shell script, you need to have ''php-cli'' (or what your package manager calls it) installed. |
The sample is given as unix shell script, you need to have ''php-cli'' (or what your package manager calls it) installed. |
||
< |
<syntaxhighlight lang=PHP>#!/usr/bin/php |
||
<?php |
<?php |
||
Line 5,489: | Line 5,489: | ||
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL); |
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample run: |
Sample run: |
||
<pre> |
<pre> |
||
Line 5,507: | Line 5,507: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
===Foreach loop=== |
===Foreach loop=== |
||
< |
<syntaxhighlight lang=picat>go1 ?=> |
||
tests(Tests), |
tests(Tests), |
||
member(Test,Tests), |
member(Test,Tests), |
||
Line 5,531: | Line 5,531: | ||
"][][", "[]][[]", "[][][][][][][][][][]", |
"][][", "[]][[]", "[][][][][][][][][][]", |
||
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]", |
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]", |
||
"[][[]][]","[[][]][]", "[][][[]][]"]).</ |
"[][[]][]","[[][]][]", "[][][[]][]"]).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,550: | Line 5,550: | ||
===DCG=== |
===DCG=== |
||
Here is an implementation using DCG (Definite Clause Grammars). |
Here is an implementation using DCG (Definite Clause Grammars). |
||
< |
<syntaxhighlight lang=Picat>go_dcg ?=> |
||
tests(Tests), |
tests(Tests), |
||
foreach(Test in Tests) |
foreach(Test in Tests) |
||
Line 5,564: | Line 5,564: | ||
balanced --> "". |
balanced --> "". |
||
balanced --> "[", balanced, "]", balanced.</ |
balanced --> "[", balanced, "]", balanced.</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang=PicoLisp>(load "@lib/simul.l") # For 'shuffle' |
||
(de generateBrackets (N) |
(de generateBrackets (N) |
||
Line 5,583: | Line 5,583: | ||
(for N 10 |
(for N 10 |
||
(prinl (if (checkBrackets (prin (generateBrackets N))) " OK" "not OK")) )</ |
(prinl (if (checkBrackets (prin (generateBrackets N))) " OK" "not OK")) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>[] OK |
<pre>[] OK |
||
Line 5,597: | Line 5,597: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang=pli>*process m or(!) s attributes source; |
||
cb: Proc Options(main); |
cb: Proc Options(main); |
||
/* PL/I program to check for balanced brackets [] ******************** |
/* PL/I program to check for balanced brackets [] ******************** |
||
Line 5,658: | Line 5,658: | ||
End; |
End; |
||
End;</ |
End;</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> balanced '' |
<pre> balanced '' |
||
Line 5,689: | Line 5,689: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{works with|PowerShell|2}} |
{{works with|PowerShell|2}} |
||
< |
<syntaxhighlight lang=PowerShell> |
||
function Get-BalanceStatus ( $String ) |
function Get-BalanceStatus ( $String ) |
||
{ |
{ |
||
Line 5,708: | Line 5,708: | ||
return $Status |
return $Status |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=PowerShell> |
||
# Test |
# Test |
||
$Strings = @( "" ) |
$Strings = @( "" ) |
||
Line 5,718: | Line 5,718: | ||
$String.PadRight( 12, " " ) + (Get-BalanceStatus $String) |
$String.PadRight( 12, " " ) + (Get-BalanceStatus $String) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,731: | Line 5,731: | ||
===PowerShell (Regex Version)=== |
===PowerShell (Regex Version)=== |
||
< |
<syntaxhighlight lang=PowerShell> |
||
function Test-BalancedBracket |
function Test-BalancedBracket |
||
{ |
{ |
||
Line 5,789: | Line 5,789: | ||
"{0}: {1}" -f $s.PadRight(8), "$(if (Test-BalancedBracket Brace $s) {'Is balanced.'} else {'Is not balanced.'})" |
"{0}: {1}" -f $s.PadRight(8), "$(if (Test-BalancedBracket Brace $s) {'Is balanced.'} else {'Is not balanced.'})" |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 5,803: | Line 5,803: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
DCG are very usefull for this kind of exercice ! |
DCG are very usefull for this kind of exercice ! |
||
< |
<syntaxhighlight lang=Prolog>rosetta_brackets :- |
||
test_brackets([]), |
test_brackets([]), |
||
test_brackets(['[',']']), |
test_brackets(['[',']']), |
||
Line 5,855: | Line 5,855: | ||
bracket(0) --> ['[']. |
bracket(0) --> ['[']. |
||
bracket(1) --> [']']. |
bracket(1) --> [']']. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output : |
Sample output : |
||
<pre> ?- balanced_brackets. |
<pre> ?- balanced_brackets. |
||
Line 5,882: | Line 5,882: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang=PureBasic>Procedure.s Generate(N) |
||
For i=1 To N |
For i=1 To N |
||
sample$+"[]" |
sample$+"[]" |
||
Line 5,925: | Line 5,925: | ||
PrintN(" is not balanced") |
PrintN(" is not balanced") |
||
EndIf |
EndIf |
||
Next</ |
Next</syntaxhighlight> |
||
Output sample |
Output sample |
||
<pre> |
<pre> |
||
Line 5,937: | Line 5,937: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang=python>>>> def gen(N): |
||
... txt = ['[', ']'] * N |
... txt = ['[', ']'] * N |
||
... random.shuffle( txt ) |
... random.shuffle( txt ) |
||
Line 5,963: | Line 5,963: | ||
'[[]]]]][]][[[[' is not balanced |
'[[]]]]][]][[[[' is not balanced |
||
'[[[[]][]]][[][]]' is balanced |
'[[[[]][]]][[][]]' is balanced |
||
'][[][[]]][]]][[[[]' is not balanced</ |
'][[][[]]][]]][[[[]' is not balanced</syntaxhighlight> |
||
=== Functional === |
=== Functional === |
||
Line 5,969: | Line 5,969: | ||
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. |
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. |
||
< |
<syntaxhighlight lang=python>>>> from itertools import accumulate |
||
>>> from random import shuffle |
>>> from random import shuffle |
||
>>> def gen(n): |
>>> def gen(n): |
||
Line 5,992: | Line 5,992: | ||
'][]][][[]][[][' is not balanced |
'][]][][[]][[][' is not balanced |
||
'][[]]][][[]][[[]' is not balanced |
'][[]]][][[]][[[]' is not balanced |
||
'][[][[]]]][[[]][][' is not balanced</ |
'][[][[]]]][[[]][][' is not balanced</syntaxhighlight> |
||
=== Array Programming === |
=== Array Programming === |
||
Line 5,998: | Line 5,998: | ||
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. |
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. |
||
< |
<syntaxhighlight lang=python>>>> import numpy as np |
||
>>> from random import shuffle |
>>> from random import shuffle |
||
>>> def gen(n): |
>>> def gen(n): |
||
Line 6,022: | Line 6,022: | ||
'[][[[]][[]]][]' is balanced |
'[][[[]][[]]][]' is balanced |
||
'[[][][[]]][[[]]]' is balanced |
'[[][][[]]][[[]]]' is balanced |
||
'][]][][[]][]][][[[' is not balanced</ |
'][]][][[]][]][][[[' is not balanced</syntaxhighlight> |
||
=={{header|Qi}}== |
=={{header|Qi}}== |
||
< |
<syntaxhighlight lang=qi>(define balanced-brackets-0 |
||
[] 0 -> true |
[] 0 -> true |
||
[] _ -> false |
[] _ -> false |
||
Line 6,048: | Line 6,048: | ||
(balanced-brackets "[]][[]") |
(balanced-brackets "[]][[]") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang=Quackery> [ char [ over of |
||
swap |
swap |
||
char ] swap of |
char ] swap of |
||
Line 6,072: | Line 6,072: | ||
[ say "un" ] |
[ say "un" ] |
||
say "balanced." |
say "balanced." |
||
cr ]</ |
cr ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,091: | Line 6,091: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang=r>balanced <- function(str){ |
||
str <- strsplit(str, "")[[1]] |
str <- strsplit(str, "")[[1]] |
||
str <- ifelse(str=='[', 1, -1) |
str <- ifelse(str=='[', 1, -1) |
||
all(cumsum(str) >= 0) && sum(str) == 0 |
all(cumsum(str) >= 0) && sum(str) == 0 |
||
}</ |
}</syntaxhighlight> |
||
Alternately, using perl 5.10-compatible regexps, |
Alternately, using perl 5.10-compatible regexps, |
||
< |
<syntaxhighlight lang=r>balanced <- function(str) { |
||
regexpr('^(\\[(?1)*\\])*$', str, perl=TRUE) > -1 |
regexpr('^(\\[(?1)*\\])*$', str, perl=TRUE) > -1 |
||
}</ |
}</syntaxhighlight> |
||
To generate some some examples: |
To generate some some examples: |
||
< |
<syntaxhighlight lang=R>rand.parens <- function(n) paste(sample(c("[","]"),2*n,replace=T),collapse="") |
||
as.data.frame(within(list(), { |
as.data.frame(within(list(), { |
||
parens <- replicate(10, rand.parens(sample.int(10,size=1))) |
parens <- replicate(10, rand.parens(sample.int(10,size=1))) |
||
balanced <- sapply(parens, balanced) |
balanced <- sapply(parens, balanced) |
||
}))</ |
}))</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang=r> balanced parens |
||
1 FALSE ][][ |
1 FALSE ][][ |
||
2 FALSE [][[]]][[]][]]][[[ |
2 FALSE [][[]]][[]][]]][[[ |
||
Line 6,123: | Line 6,123: | ||
8 FALSE []]]][[[]][[[] |
8 FALSE []]]][[[]][[[] |
||
9 TRUE [[[[][[][]]]]] |
9 TRUE [[[[][[][]]]]] |
||
10 TRUE []</ |
10 TRUE []</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang=Racket> |
||
#lang racket |
#lang racket |
||
Line 6,145: | Line 6,145: | ||
(for ([n 10]) (try n)) |
(for ([n 10]) (try n)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 6,154: | Line 6,154: | ||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang=raku lines>sub balanced($s) { |
||
my $l = 0; |
my $l = 0; |
||
for $s.comb { |
for $s.comb { |
||
Line 6,170: | Line 6,170: | ||
my $n = prompt "Number of brackets"; |
my $n = prompt "Number of brackets"; |
||
my $s = (<[ ]> xx $n).flat.pick(*).join; |
my $s = (<[ ]> xx $n).flat.pick(*).join; |
||
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</ |
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</syntaxhighlight> |
||
===FP oriented=== |
===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. |
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. |
||
<lang |
<syntaxhighlight lang=raku lines>sub balanced($s) { |
||
.none < 0 and .[*-1] == 0 |
.none < 0 and .[*-1] == 0 |
||
given ([\+] '\\' «leg« $s.comb).cache; |
given ([\+] '\\' «leg« $s.comb).cache; |
||
Line 6,181: | Line 6,181: | ||
my $n = prompt "Number of bracket pairs: "; |
my $n = prompt "Number of bracket pairs: "; |
||
my $s = <[ ]>.roll($n*2).join; |
my $s = <[ ]>.roll($n*2).join; |
||
say "$s { balanced($s) ?? "is" !! "is not" } well-balanced"</ |
say "$s { balanced($s) ?? "is" !! "is not" } well-balanced"</syntaxhighlight> |
||
===String munging=== |
===String munging=== |
||
Of course, a Perl 5 programmer might just remove as many inner balanced pairs as possible and then see what's left. |
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}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang=raku lines>sub balanced($_ is copy) { |
||
Nil while s:g/'[]'//; |
Nil while s:g/'[]'//; |
||
$_ eq ''; |
$_ eq ''; |
||
Line 6,193: | Line 6,193: | ||
my $n = prompt "Number of bracket pairs: "; |
my $n = prompt "Number of bracket pairs: "; |
||
my $s = <[ ]>.roll($n*2).join; |
my $s = <[ ]>.roll($n*2).join; |
||
say "$s is", ' not' x not balanced($s), " well-balanced";</ |
say "$s is", ' not' x not balanced($s), " well-balanced";</syntaxhighlight> |
||
===Parsing with a grammar=== |
===Parsing with a grammar=== |
||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang=raku lines>grammar BalBrack { token TOP { '[' <TOP>* ']' } } |
||
my $n = prompt "Number of bracket pairs: "; |
my $n = prompt "Number of bracket pairs: "; |
||
my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join; |
my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join; |
||
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";</ |
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang=Red>; Functional code |
||
balanced-brackets: [#"[" any balanced-brackets #"]"] |
balanced-brackets: [#"[" any balanced-brackets #"]"] |
||
rule: [any balanced-brackets end] |
rule: [any balanced-brackets end] |
||
Line 6,225: | Line 6,225: | ||
str: random copy/part "[][][][][][][][][][]" i * 2 |
str: random copy/part "[][][][][][][][][][]" i * 2 |
||
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]] |
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]] |
||
]</ |
]</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===with 40 examples=== |
===with 40 examples=== |
||
< |
<syntaxhighlight lang=rexx>/*REXX program checks for balanced brackets [ ] ─── some fixed, others random.*/ |
||
parse arg seed . /*obtain optional argument from the CL.*/ |
parse arg seed . /*obtain optional argument from the CL.*/ |
||
if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/ |
if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/ |
||
Line 6,267: | Line 6,267: | ||
else do; !=!-1; if !<0 then return 0; end |
else do; !=!-1; if !<0 then return 0; end |
||
end /*j*/ |
end /*j*/ |
||
return !==0 /* [↑] "!" is the nested ][ counter.*/</ |
return !==0 /* [↑] "!" is the nested ][ counter.*/</syntaxhighlight> |
||
'''output''' using the (some internal, others random) expressions: |
'''output''' using the (some internal, others random) expressions: |
||
<pre> |
<pre> |
||
Line 6,313: | Line 6,313: | ||
===with examples + 30 permutations=== |
===with examples + 30 permutations=== |
||
< |
<syntaxhighlight lang=rexx> |
||
/*REXX program to check for balanced brackets [] ********************** |
/*REXX program to check for balanced brackets [] ********************** |
||
* test strings and random string generation copied from Version 1 |
* test strings and random string generation copied from Version 1 |
||
Line 6,381: | Line 6,381: | ||
end |
end |
||
return nest=0 /* nest=0 -> balanced */ |
return nest=0 /* nest=0 -> balanced */ |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,430: | Line 6,430: | ||
Naturally, each of the one hundred thousand character strings aren't displayed (for balanced/not-balanced), |
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. |
<br>but a count is displayed, as anyone can generate the same strings in other languages and compare results. |
||
< |
<syntaxhighlight lang=rexx>/*REXX program checks for around 125,000 generated balanced brackets expressions [ ] */ |
||
bals=0 |
bals=0 |
||
#=0; do j=1 until L>20 /*generate lots of bracket permutations*/ |
#=0; do j=1 until L>20 /*generate lots of bracket permutations*/ |
||
Line 6,450: | Line 6,450: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
countStr: procedure; parse arg n,h,s; if s=='' then s=1; w=length(n) |
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</ |
do r=0 until _==0; _=pos(n,h,s); s=_+w; end; return r</syntaxhighlight> |
||
'''output''' when using the default input: |
'''output''' when using the default input: |
||
<pre> |
<pre> |
||
Line 6,457: | Line 6,457: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
nr = 0 |
nr = 0 |
||
while nr < 10 |
while nr < 10 |
||
Line 6,484: | Line 6,484: | ||
next |
next |
||
return "ok." |
return "ok." |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 6,502: | Line 6,502: | ||
{{trans|D}} |
{{trans|D}} |
||
{{works with|Ruby|1.9}} |
{{works with|Ruby|1.9}} |
||
< |
<syntaxhighlight lang=ruby>re = /\A # beginning of string |
||
(?<bb> # begin capture group <bb> |
(?<bb> # begin capture group <bb> |
||
\[ # literal [ |
\[ # literal [ |
||
Line 6,518: | Line 6,518: | ||
t = s.gsub(/[^\[\]]/, "") |
t = s.gsub(/[^\[\]]/, "") |
||
puts (t =~ re ? " OK: " : "bad: ") + s |
puts (t =~ re ? " OK: " : "bad: ") + s |
||
end</ |
end</syntaxhighlight> |
||
One output: <pre> |
One output: <pre> |
||
Line 6,537: | Line 6,537: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang=runbasic>dim brk$(10) |
||
brk$(1) = "[[[][]]]" |
brk$(1) = "[[[][]]]" |
||
brk$(2) = "[[[]][[[][[][]]]]]" |
brk$(2) = "[[[]][[[][[][]]]]]" |
||
Line 6,557: | Line 6,557: | ||
if trim$(b$) = "" then print " OK "; else print "Not OK "; |
if trim$(b$) = "" then print " OK "; else print "Not OK "; |
||
print brk$(i) |
print brk$(i) |
||
next i</ |
next i</syntaxhighlight> |
||
One output: <pre> OK |
One output: <pre> OK |
||
Line 6,575: | Line 6,575: | ||
{{libheader|rand}} |
{{libheader|rand}} |
||
< |
<syntaxhighlight lang=rust>extern crate rand; |
||
trait Balanced { |
trait Balanced { |
||
Line 6,614: | Line 6,614: | ||
println!("{} {}", brackets, brackets.is_balanced()) |
println!("{} {}", brackets, brackets.is_balanced()) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: <pre> |
Output: <pre> |
||
true |
true |
||
Line 6,634: | Line 6,634: | ||
=== Scala Version 1 === |
=== Scala Version 1 === |
||
{{works with|Scala|2.9.1}} |
{{works with|Scala|2.9.1}} |
||
< |
<syntaxhighlight lang=scala>import scala.collection.mutable.ListBuffer |
||
import scala.util.Random |
import scala.util.Random |
||
Line 6,669: | Line 6,669: | ||
println("\n"+"check all permutations of given length:") |
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)) |
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1)) |
||
}</ |
}</syntaxhighlight> |
||
<pre style="height:30ex;overflow:scroll">arbitrary random order: |
<pre style="height:30ex;overflow:scroll">arbitrary random order: |
||
Line 7,045: | Line 7,045: | ||
=== Scala Version 2 === |
=== Scala Version 2 === |
||
{{works with|Scala|2.10.1}} |
{{works with|Scala|2.10.1}} |
||
< |
<syntaxhighlight lang=scala>import scala.util.Random.shuffle |
||
object BalancedBracketsApp extends App { |
object BalancedBracketsApp extends App { |
||
Line 7,072: | Line 7,072: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Alternate implementation of "isBalanced" using tail-recursion instead of var and return: |
Alternate implementation of "isBalanced" using tail-recursion instead of var and return: |
||
< |
<syntaxhighlight lang=scala>import scala.util.Random.shuffle |
||
import scala.annotation.tailrec |
import scala.annotation.tailrec |
||
Line 7,095: | Line 7,095: | ||
isBalanced(rest, newBalance) |
isBalanced(rest, newBalance) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Slightly modified implementation of "isBalanced" using tail-recursion |
Slightly modified implementation of "isBalanced" using tail-recursion |
||
{{works with|Scala|2.11.7}} |
{{works with|Scala|2.11.7}} |
||
< |
<syntaxhighlight lang=scala> |
||
@scala.annotation.tailrec |
@scala.annotation.tailrec |
||
final def isBalanced( |
final def isBalanced( |
||
Line 7,118: | Line 7,118: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output: |
Sample output: |
||
Line 7,135: | Line 7,135: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang=scheme>(define (balanced-brackets string) |
||
(define (b chars sum) |
(define (b chars sum) |
||
(cond ((< sum 0) |
(cond ((< sum 0) |
||
Line 7,160: | Line 7,160: | ||
(balanced-brackets "][][") |
(balanced-brackets "][][") |
||
(balanced-brackets "[]][[]") |
(balanced-brackets "[]][[]") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scilab}}== |
=={{header|Scilab}}== |
||
{{trans|MATLAB}} |
{{trans|MATLAB}} |
||
<lang>function varargout=isbb(s) |
<syntaxhighlight lang=text>function varargout=isbb(s) |
||
st=strsplit(s); |
st=strsplit(s); |
||
t=cumsum((st=='[')-(st==']')); |
t=cumsum((st=='[')-(st==']')); |
||
balanced=and(t>=0) & t(length(t))==0; |
balanced=and(t>=0) & t(length(t))==0; |
||
varargout=list(balanced) |
varargout=list(balanced) |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
{{out}} |
{{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>. |
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>. |
||
<lang>for j=[5 16 22] |
<syntaxhighlight lang=text>for j=[5 16 22] |
||
s=[]; |
s=[]; |
||
for i=1:j |
for i=1:j |
||
Line 7,185: | Line 7,185: | ||
x=isbb(s); |
x=isbb(s); |
||
disp(x); |
disp(x); |
||
end</ |
end</syntaxhighlight> |
||
Console output: |
Console output: |
||
<pre> ][]][ |
<pre> ][]][ |
||
Line 7,200: | Line 7,200: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
const func string: generateBrackets (in integer: count) is func |
const func string: generateBrackets (in integer: count) is func |
||
Line 7,252: | Line 7,252: | ||
end for; |
end for; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 7,274: | Line 7,274: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>func balanced (str) { |
||
var depth = 0 |
var depth = 0 |
||
Line 7,287: | Line 7,287: | ||
for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] { |
for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] { |
||
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str) |
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 7,301: | Line 7,301: | ||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
< |
<syntaxhighlight lang=simula>BEGIN |
||
INTEGER U; |
INTEGER U; |
||
U := ININT; |
U := ININT; |
||
Line 7,346: | Line 7,346: | ||
END; |
END; |
||
END</ |
END</syntaxhighlight> |
||
{{in}} |
{{in}} |
||
<pre>710</pre> |
<pre>710</pre> |
||
Line 7,396: | Line 7,396: | ||
{{works with|PolyML}} |
{{works with|PolyML}} |
||
< |
<syntaxhighlight lang=sml>fun isBalanced s = checkBrackets 0 (String.explode s) |
||
and checkBrackets 0 [] = true |
and checkBrackets 0 [] = true |
||
| checkBrackets _ [] = false |
| checkBrackets _ [] = false |
||
Line 7,402: | Line 7,402: | ||
| checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest |
| checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest |
||
| checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest |
| checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest |
||
| checkBrackets counter (_::rest) = checkBrackets counter rest</ |
| checkBrackets counter (_::rest) = checkBrackets counter rest</syntaxhighlight> |
||
An example of usage |
An example of usage |
||
< |
<syntaxhighlight lang=sml>val () = |
||
List.app print |
List.app print |
||
(List.map |
(List.map |
||
Line 7,416: | Line 7,416: | ||
(* A set of strings to test *) |
(* A set of strings to test *) |
||
["", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"] |
["", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"] |
||
)</ |
)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 7,431: | Line 7,431: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang=stata>mata |
||
function random_brackets(n) { |
function random_brackets(n) { |
||
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) |
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) |
||
Line 7,442: | Line 7,442: | ||
return(all(a:>=0) & a[n]==0) |
return(all(a:>=0) & a[n]==0) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
'''Test''' |
'''Test''' |
||
Line 7,469: | Line 7,469: | ||
Checks balance function: |
Checks balance function: |
||
< |
<syntaxhighlight lang=swift>import Foundation |
||
func isBal(str: String) -> Bool { |
func isBal(str: String) -> Bool { |
||
Line 7,478: | Line 7,478: | ||
} |
} |
||
</ |
</syntaxhighlight>output:<syntaxhighlight lang=swift> |
||
isBal("[[[]]]") // true |
isBal("[[[]]]") // true |
||
isBal("[]][[]") // false |
isBal("[]][[]") // false |
||
</ |
</syntaxhighlight>Random Bracket function:<syntaxhighlight lang=swift> |
||
func randBrack(n: Int) -> String { |
func randBrack(n: Int) -> String { |
||
Line 7,499: | Line 7,499: | ||
} |
} |
||
</ |
</syntaxhighlight>output:<syntaxhighlight lang=swift> |
||
randBrack(2) // "]][[" |
randBrack(2) // "]][[" |
||
</ |
</syntaxhighlight>Random check balance function:<syntaxhighlight lang=swift> |
||
func randIsBal(n: Int) { |
func randIsBal(n: Int) { |
||
Line 7,518: | Line 7,518: | ||
randIsBal(4) |
randIsBal(4) |
||
</ |
</syntaxhighlight>output:<syntaxhighlight lang=swift> |
||
// ][ is unbalanced |
// ][ is unbalanced |
||
Line 7,526: | Line 7,526: | ||
// []][[] is unbalanced |
// []][[] is unbalanced |
||
// |
// |
||
// [][][[]] is balanced</ |
// [][][[]] is balanced</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang=tcl>proc generate {n} { |
||
if {!$n} return |
if {!$n} return |
||
set l [lrepeat $n "\[" "\]"] |
set l [lrepeat $n "\[" "\]"] |
||
Line 7,556: | Line 7,556: | ||
set s [generate $i] |
set s [generate $i] |
||
puts "\"$s\"\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]" |
puts "\"$s\"\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]" |
||
}</ |
}</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 7,577: | Line 7,577: | ||
===Constructing correctly balanced strings=== |
===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: |
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: |
||
< |
<syntaxhighlight lang=tcl>proc constructBalancedString {n} { |
||
set s "" |
set s "" |
||
for {set i 0} {$i < $n} {incr i} { |
for {set i 0} {$i < $n} {incr i} { |
||
Line 7,584: | Line 7,584: | ||
} |
} |
||
return $s |
return $s |
||
}</ |
}</syntaxhighlight> |
||
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). |
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,591: | Line 7,591: | ||
Generation program in Unix TMG: |
Generation program in Unix TMG: |
||
< |
<syntaxhighlight lang=UnixTMG>program: readint(n) [n>0] readint(seed) |
||
loop: parse(render) [--n>0?]/done loop; |
loop: parse(render) [--n>0?]/done loop; |
||
render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * }; |
render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * }; |
||
Line 7,609: | Line 7,609: | ||
>>; |
>>; |
||
n: 0; i: 0; b: 0; seed: 0;</ |
n: 0; i: 0; b: 0; seed: 0;</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 7,619: | Line 7,619: | ||
Analysis can be done easily using grammar specification, rather than counting brackets: |
Analysis can be done easily using grammar specification, rather than counting brackets: |
||
< |
<syntaxhighlight lang=UnixTMG>loop: parse(corr)\loop parse(incorr)\loop; |
||
corr: brkts * = { < OK: > 1 * }; |
corr: brkts * = { < OK: > 1 * }; |
||
brkts: brkt/null brkts = { 2 1 }; |
brkts: brkt/null brkts = { 2 1 }; |
||
Line 7,629: | Line 7,629: | ||
nonl: !<< |
nonl: !<< |
||
>>;</ |
>>;</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 7,642: | Line 7,642: | ||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang=tuscript> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
Line 7,672: | Line 7,672: | ||
PRINT b," ",status |
PRINT b," ",status |
||
ENDLOOP |
ENDLOOP |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 7,692: | Line 7,692: | ||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
< |
<syntaxhighlight lang=txr>@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end) |
||
@(do (defvar r (make-random-state nil)) |
@(do (defvar r (make-random-state nil)) |
||
Line 7,714: | Line 7,714: | ||
@{parens 15} @{matched 15} @{mismatched 15} |
@{parens 15} @{matched 15} @{mismatched 15} |
||
@ (end) |
@ (end) |
||
@(end)</ |
@(end)</syntaxhighlight> |
||
The recursive pattern function <code>@(paren)</code> gives rise to a grammar which matches parentheses: |
The recursive pattern function <code>@(paren)</code> gives rise to a grammar which matches parentheses: |
||
Line 7,751: | Line 7,751: | ||
== {{header|TypeScript}} == |
== {{header|TypeScript}} == |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<syntaxhighlight lang=javascript>// Balanced brackets |
||
function isStringBalanced(str: string): bool { |
function isStringBalanced(str: string): bool { |
||
Line 7,795: | Line 7,795: | ||
console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK.")}`); |
console.log(`The string '${test}' is ${(isStringBalanced(test) ? "OK." : "not OK.")}`); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 7,822: | Line 7,822: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang=bash>generate() { |
||
local b=() |
local b=() |
||
local i j tmp |
local i j tmp |
||
Line 7,859: | Line 7,859: | ||
balanced "$test" && result=OK || result="NOT OK" |
balanced "$test" && result=OK || result="NOT OK" |
||
printf "%s\t%s\n" "$test" "$result" |
printf "%s\t%s\n" "$test" "$result" |
||
done</ |
done</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 7,876: | Line 7,876: | ||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
< |
<syntaxhighlight lang=Ursala>#import std |
||
#import nat |
#import nat |
||
Line 7,883: | Line 7,883: | ||
#cast %bm |
#cast %bm |
||
main = ^(2-$'[]'*,balanced)* eql@ZFiFX*~ iota64</ |
main = ^(2-$'[]'*,balanced)* eql@ZFiFX*~ iota64</syntaxhighlight> |
||
output: |
output: |
||
<pre>< |
<pre>< |
||
Line 7,903: | Line 7,903: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<syntaxhighlight lang=vb> |
|||
<lang vb> |
|||
Public Function checkBrackets(s As String) As Boolean |
Public Function checkBrackets(s As String) As Boolean |
||
'function checks strings for balanced brackets |
'function checks strings for balanced brackets |
||
Line 7,970: | Line 7,970: | ||
Next |
Next |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
sample output: |
sample output: |
||
Line 7,990: | Line 7,990: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang=vb>For n = 1 To 10 |
||
sequence = Generate_Sequence(n) |
sequence = Generate_Sequence(n) |
||
WScript.Echo sequence & " is " & Check_Balance(sequence) & "." |
WScript.Echo sequence & " is " & Check_Balance(sequence) & "." |
||
Line 8,025: | Line 8,025: | ||
Check_Balance = "Balanced" |
Check_Balance = "Balanced" |
||
End If |
End If |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 8,042: | Line 8,042: | ||
Antother version not using libraries. The generator works as intended (more difficult to do than the checking) |
Antother version not using libraries. The generator works as intended (more difficult to do than the checking) |
||
<syntaxhighlight lang=vb> |
|||
<lang vb> |
|||
option explicit |
option explicit |
||
Line 8,083: | Line 8,083: | ||
& s & vbtab & " Checks as " & iif(bb,"","un")&"balanced" |
& s & vbtab & " Checks as " & iif(bb,"","un")&"balanced" |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample run |
Sample run |
||
<pre> |
<pre> |
||
Line 8,099: | Line 8,099: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang=vbnet>Module Module1 |
||
Private rand As New Random |
Private rand As New Random |
||
Line 8,142: | Line 8,142: | ||
Return numOpen = numClosed |
Return numOpen = numClosed |
||
End Function |
End Function |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 8,159: | Line 8,159: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang=vlang>import datatypes as dt |
||
fn is_valid(bracket string) bool { |
fn is_valid(bracket string) bool { |
||
Line 8,182: | Line 8,182: | ||
println('$b ${is_valid(b)}') |
println('$b ${is_valid(b)}') |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 8,198: | Line 8,198: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang=ecmascript>import "random" for Random |
||
var isBalanced = Fn.new { |s| |
var isBalanced = Fn.new { |s| |
||
Line 8,227: | Line 8,227: | ||
for (j in 1..8) s = s + ((rand.int(2) == 0) ? "[" : "]") |
for (j in 1..8) s = s + ((rand.int(2) == 0) ? "[" : "]") |
||
System.print("%(s) %(isBalanced.call(s) ? "OK" : "NOT OK")") |
System.print("%(s) %(isBalanced.call(s) ? "OK" : "NOT OK")") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 8,251: | Line 8,251: | ||
=={{header|X86 Assembly}}== |
=={{header|X86 Assembly}}== |
||
< |
<syntaxhighlight lang=X86Assembly> |
||
section .data |
section .data |
||
Line 8,318: | Line 8,318: | ||
syscall |
syscall |
||
ret |
ret |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|XBasic}}== |
=={{header|XBasic}}== |
||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
< |
<syntaxhighlight lang=xbasic>' Balanced brackets |
||
PROGRAM "balancedbrackets" |
PROGRAM "balancedbrackets" |
||
VERSION "0.001" |
VERSION "0.001" |
||
Line 8,422: | Line 8,422: | ||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 8,448: | Line 8,448: | ||
=={{header|XBS}}== |
=={{header|XBS}}== |
||
< |
<syntaxhighlight lang=xbs>const Chars:[string] = ["[","]"]; |
||
func GenerateString(Amount:number=4):string{ |
func GenerateString(Amount:number=4):string{ |
||
set Result:string = ""; |
set Result:string = ""; |
||
Line 8,464: | Line 8,464: | ||
set s = GenerateString(math.random(2,4)*2); |
set s = GenerateString(math.random(2,4)*2); |
||
log(`{s}: {IsBalanced(s)}`); |
log(`{s}: {IsBalanced(s)}`); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 8,480: | Line 8,480: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic code declarations |
||
int N, I, C, Nest; |
int N, I, C, Nest; |
||
Line 8,505: | Line 8,505: | ||
Text(0,"OK |
Text(0,"OK |
||
"); |
"); |
||
]</ |
]</syntaxhighlight> |
||
Example output: |
Example output: |
||
Line 8,517: | Line 8,517: | ||
=={{header|Ya}}== |
=={{header|Ya}}== |
||
< |
<syntaxhighlight lang=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 ` |
// all types are prefixed by ` |
||
Line 8,553: | Line 8,553: | ||
//@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/ 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") |
@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</ |
// 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</syntaxhighlight> |
||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang=Yabasic>sub check_brackets(s$) |
||
local level, i |
local level, i |
||
Line 8,573: | Line 8,573: | ||
if not check_brackets(s$) print "not "; |
if not check_brackets(s$) print "not "; |
||
print "ok"</ |
print "ok"</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang=zkl>fcn bb(bs){ while(a:=bs.span("[","]")) {bs=bs[a[1],*]} (Void!=a) }</syntaxhighlight> |
||
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). |
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> |
<pre> |
||
Line 8,597: | Line 8,597: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|AWK}} |
{{trans|AWK}} |
||
< |
<syntaxhighlight lang=zxbasic>10 FOR n=1 TO 7 |
||
20 READ s$ |
20 READ s$ |
||
25 PRINT "The sequence ";s$;" is "; |
25 PRINT "The sequence ";s$;" is "; |
||
Line 8,614: | Line 8,614: | ||
1100 RETURN |
1100 RETURN |
||
2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][][" |
2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][][" |
||
</syntaxhighlight> |
|||
</lang> |