Balanced brackets: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 19:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F gen(n)
V txt = [‘[’, ‘]’] * n
random:shuffle(&txt)
Line 53:
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Balanced brackets 28/04/2016
BALANCE CSECT
USING BALANCE,R13 base register and savearea pointer
Line 179:
 
=={{header|ABAP}}==
<syntaxhighlight lang=ABAP"abap">
CLASS lcl_balanced_brackets DEFINITION.
PUBLIC SECTION.
Line 303:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">PROC Generate(BYTE size CHAR ARRAY s)
BYTE i,half
 
Line 395:
Using #HASH-OFF
</pre>
<syntaxhighlight lang=Acurity"acurity Architectarchitect">
FUNCTION bBRACKETS_MATCH(zStringWithBrackets: STRING): STRING
VAR sCount: SHORT
Line 426:
=={{header|Ada}}==
brackets.adb:
<syntaxhighlight lang=Ada"ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Strings.Fixed;
Line 503:
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">unbalanced(data s)
{
integer b, i;
Line 552:
=={{header|ALGOL 68}}==
{{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 #
PROC get brackets = ( INT length ) STRING:
Line 649:
<br clear=both>
==={{header|Java}}===
<syntaxhighlight lang="text">
grammar balancedBrackets ;
 
Line 694:
and a function to check whether a given string of brackets is balanced.
 
<syntaxhighlight lang=APL"apl">gen ← (⊂+?+)⍨ ⌷ ('[]'/⍨⊢)
bal ← (((|≡⊢)+\) ∧ 0=+/)(+⌿1 ¯1×[1]'[]'∘.=⊢)</syntaxhighlight>
 
Sample run for 0..N..10:
 
<syntaxhighlight lang=APL"apl"> ↑{br←gen ⍵ ⋄ br,': ',(1+bal br)⊃'Bad' 'Good'}¨0,⍳10
: Good
[]: Good
Line 717:
(ES6 functionally composed version)
 
<syntaxhighlight lang=AppleScript"applescript">-- CHECK NESTING OF SQUARE BRACKET SEQUENCES ---------------------------------
 
-- Zero-based index of the first problem (-1 if none found):
Line 914:
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang=ARM_Assembly"arm_assembly">
.data
 
Line 977:
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">isBalanced: function [s][
cnt: 0
Line 1,016:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">; Generate 10 strings with equal left and right brackets
Loop, 5
{
Line 1,063:
 
A second example repeatedly replacing []:
<syntaxhighlight lang=AutoHotkey"autohotkey">Loop, 5
{
B = %A_Index%
Line 1,101:
 
=={{header|AutoIt}}==
<syntaxhighlight lang=AutoIt"autoit">
#include <Array.au3>
Local $Array[1]
Line 1,134:
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">#!/usr/bin/awk -f
BEGIN {
print isbb("[]")
Line 1,165:
 
=={{header|BaCon}}==
<syntaxhighlight lang="bacon">FOR len = 0 TO 18 STEP 2
 
str$ = ""
Line 1,203:
{{works with|QBasic}}
 
<syntaxhighlight lang="qbasic">DECLARE FUNCTION checkBrackets% (brackets AS STRING)
DECLARE FUNCTION generator$ (length AS INTEGER)
 
Line 1,277:
==={{header|Commodore BASIC}}===
Based on ZX Spectrum BASIC implementation
<syntaxhighlight lang="basic">10 PRINT CHR$(147): REM CLEAR SCREEN
20 FOR N=1 TO 7
30 READ S$
Line 1,302:
=={{header|BASIC256}}==
{{trans|Yabasic}}
<syntaxhighlight lang=BASIC256"basic256">s$ = "[[]][]"
print s$; " = ";
 
Line 1,327:
=={{header|Batch File}}==
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
Line 1,404:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic">FOR x%=1 TO 10
test$=FNgenerate(RND(10))
PRINT "Bracket string ";test$;" is ";FNvalid(test$)
Line 1,447:
{{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.
<syntaxhighlight lang=Befunge"befunge">v > "KO TON" ,,,,,, v
> ~ : 25*- #v_ $ | > 25*, @
> "KO" ,, ^
Line 1,462:
This allows for a particular simple implementation:
 
<syntaxhighlight lang="bqn">Gen ← (•rand.Deal⊏⥊⟜"[]") 2⊸×
Bal ← {
Mul ← {a‿b𝕊x‿y: ⟨a+0⌈x-b, y+0⌈b-x⟩}
Line 1,480:
=={{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.
<syntaxhighlight lang="bracmat">( (bal=|"[" !bal "]" !bal)
& ( generate
= a j m n z N S someNumber
Line 1,521:
 
=={{header|Brat}}==
<syntaxhighlight lang="brat">string.prototype.balanced? = {
brackets = []
balanced = true
Line 1,566:
 
=={{header|C}}==
<syntaxhighlight lang="c">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
Line 1,608:
while(n<9) doSeq(n++);
return 0;
}</syntaxhighlight>result:<syntaxhighlight lang="text">'': True
'[]': True
']][[': False
Line 1,619:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,671:
"[]]][][]][[][[" is not balanced.
"[]]][]]][[][[][[" is not balanced.</pre>
<syntaxhighlight lang="csharp">
// simple solution
string input = Console.ReadLine();
Line 1,699:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <string>
Line 1,745:
 
=={{header|Ceylon}}==
<syntaxhighlight lang=Ceylon"ceylon">import com.vasileff.ceylon.random.api {
platformRandom,
Random
Line 1,788:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">(defn gen-brackets [n]
(->> (concat (repeat n \[) (repeat n \]))
shuffle
Line 1,806:
 
* We can use <code>reduce</code> to consume the sequence:
:<syntaxhighlight lang=Clojure"clojure">(defn balanced? [s]
(empty?
(reduce
Line 1,819:
 
* Only <code>[</code>s are put on the stack. We can just count the unmatched ones.
:<syntaxhighlight lang=Clojure"clojure">(defn balanced? [s]
(let [opens-closes (->> s
(map {\[ 1, \] -1})
Line 1,843:
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs the random number generator from
% "misc.lib" that comes with PCLU.
 
Line 1,909:
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. test-balanced-brackets.
 
Line 2,009:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
isBalanced = (brackets) ->
openCount = 0
Line 2,027:
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee balanced.coffee
[[[[ false
Line 2,048:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun string-of-brackets (n)
(let* ((len (* 2 n))
Line 2,096:
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE Brackets;
IMPORT StdLog, Args, Stacks (* See Task Stacks *);
Line 2,170:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">def generate(n : Int)
(['[',']'] * n).shuffle.join # Implicit return
end
Line 2,213:
===Standard Version===
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() {
Line 2,233:
===Imperative Version===
{{trans|Raku}}
<syntaxhighlight lang="d">import std.stdio, std.random, std.range, std.algorithm;
 
bool isBalanced(in string txt) pure nothrow {
Line 2,260:
===Functional Style===
{{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 {
Line 2,282:
=={{header|Delphi}}==
 
<syntaxhighlight lang=Delphi"delphi">procedure Balanced_Brackets;
 
var BracketsStr : string;
Line 2,327:
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">matching?:
swap 0
for c in chars:
Line 2,356:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(define (balance str)
(for/fold (closed 0) ((par str))
Line 2,389:
=={{header|Elena}}==
ELENA 4.x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'text;
Line 2,452:
{{trans|Erlang}}
{{works with|Elixir|1.1}}
<syntaxhighlight lang="elixir">defmodule Balanced_brackets do
def task do
Enum.each(0..5, fn n ->
Line 2,491:
 
=={{header|Erlang}}==
<syntaxhighlight lang=Erlang"erlang">
-module( balanced_brackets ).
-export( [generate/1, is_balanced/1, task/0] ).
Line 2,534:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">function check_brackets(sequence s)
integer level
level = 0
Line 2,600:
 
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">bracketReport
=LAMBDA(bracketPair,
LAMBDA(s,
Line 2,689:
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<syntaxhighlight lang="lisp">APPENDCOLS
=LAMBDA(xs,
LAMBDA(ys,
Line 2,913:
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let isBalanced str =
let rec loop count = function
| ']'::_ when count = 0 -> false
Line 2,950:
=={{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.
<syntaxhighlight lang=Factor"factor">USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
 
Line 2,975:
Some more idiomatic solution might be as follows:
 
<syntaxhighlight lang=Factor"factor">USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
 
Line 2,999:
=={{header|Fantom}}==
 
<syntaxhighlight lang="fantom">
class Main
{
Line 3,067:
=={{header|Forth}}==
{{works with|4tH|3.61.1}}
<syntaxhighlight lang="forth">include lib/choose.4th ( n1 -- n2)
include lib/ctos.4th ( n -- a 1)
 
Line 3,105:
=={{header|Fortran}}==
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
! $ ./f
Line 3,206:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isBalanced(s As String) As Boolean
Line 3,272:
=={{header|Gambas}}==
'''[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
Line 3,366:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">Balanced := function(L)
local c, r;
r := 0;
Line 3,404:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 3,475:
=={{header|Groovy}}==
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 }
Line 3,498:
 
Check Balance of Bracket String:
<syntaxhighlight lang="groovy">boolean balancedBrackets(String brackets, int depth=0) {
if (brackets == null || brackets.empty) return depth == 0
switch (brackets[0]) {
Line 3,511:
 
Test:
<syntaxhighlight lang="groovy">Set brackets = []
(0..100).each {
(0..8).each { r ->
Line 3,722:
=={{header|Haskell}}==
The simplest solution exploits the idea of stack-based automaton, which could be implemented by a fold.
<syntaxhighlight lang="haskell">
isMatching :: String -> Bool
isMatching = null . foldl aut []
Line 3,733:
This generates an infinite stream of correct balanced brackets expressions:
 
<syntaxhighlight lang="haskell">brackets = filter isMatching
$ [1.. ] >>= (`replicateM` "[]{}") </syntaxhighlight>
<pre>λ> take 10 brackets
Line 3,740:
In case the index of unmatched opening bracket is need to be found, following solution is suitable.
 
<syntaxhighlight lang="haskell">
import Control.Monad
import System.Random
Line 3,773:
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.
<syntaxhighlight lang="haskell">module VShuffle
( shuffle
) where
Line 3,827:
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.Split (chunksOf)
Line 3,891:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon"icon">procedure main(arglist)
every s := genbs(!arglist) do
write(image(s), if isbalanced(s) then " is balanced." else " is unbalanced")
Line 3,923:
 
=={{header|J}}==
'''Solution''': <syntaxhighlight lang="j">bracketDepth =: '[]' -&(+/\)/@:(=/) ]
checkBalanced =: _1 -.@e. bracketDepth
genBracketPairs =: (?~@# { ])@#"0 1&'[]' NB. bracket pairs in arbitrary order</syntaxhighlight>
'''Examples''':<syntaxhighlight lang="j"> (, ' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10
OK
][ bad
Line 3,943:
=={{header|Java}}==
{{works with|Java|1.5+}}
<syntaxhighlight lang="java5">public class BalancedBrackets {
 
public static boolean hasBalancedBrackets(String str) {
Line 4,011:
 
=== Extended ===
<syntaxhighlight lang="java">import java.util.ArrayDeque;
import java.util.Deque;
 
Line 4,101:
====Iterative====
 
<syntaxhighlight lang=JavaScript"javascript">function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
Line 4,144:
==== Another solution ====
{{works with|Node.js}}
<syntaxhighlight lang=JavaScript"javascript">
console.log("Supplied examples");
var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"];
Line 4,229:
====Functional====
With visual indication of where the balance fails:
<syntaxhighlight lang=JavaScript"javascript">(() => {
'use strict';
 
Line 4,348:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Printf
 
function balancedbrackets(str::AbstractString)
Line 4,377:
 
'''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}}==
<syntaxhighlight lang=K"k">
gen_brackets:{"[]"@x _draw 2}
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)}
Line 4,398:
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">"[[]][]]"
 
%acc 0 !acc
Line 4,419:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="scala">import java.util.Random
 
fun isBalanced(s: String): Boolean {
Line 4,474:
 
=={{header|L++}}==
<syntaxhighlight lang="lisp">(include "string")
(defn bool balanced (std::string s)
Line 4,491:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">define randomparens(num::integer,open::string='[',close::string=']') => {
local(out) = array
 
Line 4,526:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print "Supplied examples"
for i =1 to 7
Line 4,612:
 
=={{header|Lua}}==
<syntaxhighlight lang=Lua"lua">
function isBalanced(s)
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.
Line 4,637:
=={{header|Maple}}==
This functionality is provided by Maple.
<syntaxhighlight lang=Maple"maple">
> use StringTools in
> IsBalanced( "", "[", "]" );
Line 4,671:
</syntaxhighlight>
Furthermore, Maple can check whether multiple fences are balanced in the same string.
<syntaxhighlight lang=Maple"maple">
> StringTools:-IsBalanced( "[()()]", "[(", "])" );
true
Line 4,677:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">(* Generate open/close events. *)
gen[n_] := RandomSample[Table[{1, -1}, {n}] // Flatten]
 
Line 4,693:
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">function x = isbb(s)
t = cumsum((s=='[') - (s==']'));
x = all(t>=0) && (t(end)==0);
Line 4,715:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">brack(s) := block(
[n: slength(s), r: 0, c],
catch(
Line 4,748:
 
=={{header|Mercury}}==
<syntaxhighlight lang=Mercury"mercury">
:- module balancedbrackets.
:- interface.
Line 4,795:
We start by defining a function:
 
<syntaxhighlight lang=MiniScript"miniscript">isBalanced = function(str)
level = 0
for c in str
Line 4,807:
We can evaluate the example strings with this code:
 
<syntaxhighlight lang=MiniScript"miniscript">examples = [
"",
"[]",
Line 4,836:
{{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.
<syntaxhighlight lang="modula2">
MODULE Brackets;
IMPORT IO, Lib;
Line 4,901:
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang=Nanoquery"nanoquery">import Nanoquery.Util
 
def gen(N)
Line 4,948:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
from random import random, randomize, shuffle
from strutils import repeat
Line 4,987:
=={{header|Oberon-2}}==
{{works with|oo2c version 2}}
<syntaxhighlight lang="oberon2">
MODULE BalancedBrackets;
IMPORT
Line 5,102:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
bundle Default {
class Balanced {
Line 5,148:
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">let generate_brackets n =
let rec aux i acc =
if i <= 0 then acc else
Line 5,183:
=={{header|Oforth}}==
 
<syntaxhighlight lang=Oforth"oforth">String method: isBalanced
| c |
0 self forEach: c [
Line 5,211:
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
 
Line 5,280:
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="oxygenbasic">function CheckBrackets(string s) as bool
'=======================================
sys co, le=len s
Line 5,310:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">balanced(s)={
my(n=0,v=Vecsmall(s));
for(i=1,#v,
Line 5,331:
Idiomatic solution, using a regex that performs subpattern recursion ''(works with Perl 5.10 and newer)'':
 
<syntaxhighlight lang=Perl"perl">sub generate {
my $n = shift;
my $str = '[' x $n;
Line 5,362:
If input strings are allowed to contain unrelated characters, this can be extended to:
 
<syntaxhighlight lang=Perl"perl">sub balanced {
shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x;
}</syntaxhighlight>
Line 5,368:
<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"perl">use Regexp::Common 'balanced';
my $re = qr/^$RE{balanced}{-parens=>'[]'}$/;
sub balanced {
Line 5,376:
Alternative implementation, using straightforward depth counting:
 
<syntaxhighlight lang=Perl"perl">sub balanced {
my $depth = 0;
for (split //, shift) {
Line 5,386:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<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>
Line 5,435:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">"[[]][]"
0 var acc
 
Line 5,456:
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"php">#!/usr/bin/php
<?php
 
Line 5,507:
=={{header|Picat}}==
===Foreach loop===
<syntaxhighlight lang="picat">go1 ?=>
tests(Tests),
member(Test,Tests),
Line 5,550:
===DCG===
Here is an implementation using DCG (Definite Clause Grammars).
<syntaxhighlight lang=Picat"picat">go_dcg ?=>
tests(Tests),
foreach(Test in Tests)
Line 5,567:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(load "@lib/simul.l") # For 'shuffle'
 
(de generateBrackets (N)
Line 5,597:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">*process m or(!) s attributes source;
cb: Proc Options(main);
/* PL/I program to check for balanced brackets [] ********************
Line 5,689:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang=PowerShell"powershell">
function Get-BalanceStatus ( $String )
{
Line 5,709:
}
</syntaxhighlight>
<syntaxhighlight lang=PowerShell"powershell">
# Test
$Strings = @( "" )
Line 5,731:
 
===PowerShell (Regex Version)===
<syntaxhighlight lang=PowerShell"powershell">
function Test-BalancedBracket
{
Line 5,803:
=={{header|Prolog}}==
DCG are very usefull for this kind of exercice !
<syntaxhighlight lang=Prolog"prolog">rosetta_brackets :-
test_brackets([]),
test_brackets(['[',']']),
Line 5,882:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure.s Generate(N)
For i=1 To N
sample$+"[]"
Line 5,937:
=={{header|Python}}==
===Procedural===
<syntaxhighlight lang="python">>>> def gen(N):
... txt = ['[', ']'] * N
... random.shuffle( txt )
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.
 
<syntaxhighlight lang="python">>>> from itertools import accumulate
>>> from random import shuffle
>>> def gen(n):
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.
 
<syntaxhighlight lang="python">>>> import numpy as np
>>> from random import shuffle
>>> def gen(n):
Line 6,026:
=={{header|Qi}}==
 
<syntaxhighlight lang="qi">(define balanced-brackets-0
[] 0 -> true
[] _ -> false
Line 6,052:
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery"> [ char [ over of
swap
char ] swap of
Line 6,091:
=={{header|R}}==
 
<syntaxhighlight lang="r">balanced <- function(str){
str <- strsplit(str, "")[[1]]
str <- ifelse(str=='[', 1, -1)
Line 6,099:
Alternately, using perl 5.10-compatible regexps,
 
<syntaxhighlight lang="r">balanced <- function(str) {
regexpr('^(\\[(?1)*\\])*$', str, perl=TRUE) > -1
}</syntaxhighlight>
Line 6,105:
To generate some some examples:
 
<syntaxhighlight lang=R"r">rand.parens <- function(n) paste(sample(c("[","]"),2*n,replace=T),collapse="")
 
as.data.frame(within(list(), {
Line 6,113:
 
Output:
<syntaxhighlight lang="r"> balanced parens
1 FALSE ][][
2 FALSE [][[]]][[]][]]][[[
Line 6,127:
=={{header|Racket}}==
 
<syntaxhighlight lang=Racket"racket">
#lang racket
 
Line 6,154:
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" linesline>sub balanced($s) {
my $l = 0;
for $s.comb {
Line 6,174:
===FP oriented===
Here's a more idiomatic solution using a hyperoperator to compare all the characters to a backslash (which is between the brackets in ASCII), a triangle reduction to return the running sum, a <tt>given</tt> to make that list the topic, and then a topicalized junction and a topicalized subscript to test the criteria for balance.
<syntaxhighlight lang="raku" linesline>sub balanced($s) {
.none < 0 and .[*-1] == 0
given ([\+] '\\' «leg« $s.comb).cache;
Line 6,186:
Of course, a Perl 5 programmer might just remove as many inner balanced pairs as possible and then see what's left.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" linesline>sub balanced($_ is copy) {
Nil while s:g/'[]'//;
$_ eq '';
Line 6,197:
===Parsing with a grammar===
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" linesline>grammar BalBrack { token TOP { '[' <TOP>* ']' } }
 
my $n = prompt "Number of bracket pairs: ";
Line 6,204:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">; Functional code
balanced-brackets: [#"[" any balanced-brackets #"]"]
rule: [any balanced-brackets end]
Line 6,229:
=={{header|REXX}}==
===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.*/
if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/
Line 6,313:
 
===with examples + 30 permutations===
<syntaxhighlight lang="rexx">
/*REXX program to check for balanced brackets [] **********************
* test strings and random string generation copied from Version 1
Line 6,430:
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.
<syntaxhighlight lang="rexx">/*REXX program checks for around 125,000 generated balanced brackets expressions [ ] */
bals=0
#=0; do j=1 until L>20 /*generate lots of bracket permutations*/
Line 6,457:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
nr = 0
while nr < 10
Line 6,502:
{{trans|D}}
{{works with|Ruby|1.9}}
<syntaxhighlight lang="ruby">re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
Line 6,537:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">dim brk$(10)
brk$(1) = "[[[][]]]"
brk$(2) = "[[[]][[[][[][]]]]]"
Line 6,575:
 
{{libheader|rand}}
<syntaxhighlight lang="rust">extern crate rand;
 
trait Balanced {
Line 6,634:
=== Scala Version 1 ===
{{works with|Scala|2.9.1}}
<syntaxhighlight lang="scala">import scala.collection.mutable.ListBuffer
import scala.util.Random
 
Line 7,045:
=== Scala Version 2 ===
{{works with|Scala|2.10.1}}
<syntaxhighlight lang="scala">import scala.util.Random.shuffle
 
object BalancedBracketsApp extends App {
Line 7,076:
Alternate implementation of "isBalanced" using tail-recursion instead of var and return:
 
<syntaxhighlight lang="scala">import scala.util.Random.shuffle
import scala.annotation.tailrec
 
Line 7,099:
Slightly modified implementation of "isBalanced" using tail-recursion
{{works with|Scala|2.11.7}}
<syntaxhighlight lang="scala">
@scala.annotation.tailrec
final def isBalanced(
Line 7,135:
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(define (balanced-brackets string)
(define (b chars sum)
(cond ((< sum 0)
Line 7,164:
=={{header|Scilab}}==
{{trans|MATLAB}}
<syntaxhighlight lang="text">function varargout=isbb(s)
st=strsplit(s);
t=cumsum((st=='[')-(st==']'));
Line 7,172:
{{out}}
The following code was used to generate random strings of length 5, 16, and 22 chars. It also displays the generated string, and the output (true of false) of <code>isbb()</code>.
<syntaxhighlight lang="text">for j=[5 16 22]
s=[];
for i=1:j
Line 7,200:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: generateBrackets (in integer: count) is func
Line 7,274:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func balanced (str) {
 
var depth = 0
Line 7,301:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
INTEGER U;
U := ININT;
Line 7,396:
{{works with|PolyML}}
 
<syntaxhighlight lang="sml">fun isBalanced s = checkBrackets 0 (String.explode s)
and checkBrackets 0 [] = true
| checkBrackets _ [] = false
Line 7,406:
An example of usage
 
<syntaxhighlight lang="sml">val () =
List.app print
(List.map
Line 7,431:
=={{header|Stata}}==
 
<syntaxhighlight lang="stata">mata
function random_brackets(n) {
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],""))
Line 7,469:
Checks balance function:
 
<syntaxhighlight lang="swift">import Foundation
 
func isBal(str: String) -> Bool {
Line 7,478:
}
</syntaxhighlight>output:<syntaxhighlight lang="swift">
isBal("[[[]]]") // true
 
isBal("[]][[]") // false
 
</syntaxhighlight>Random Bracket function:<syntaxhighlight lang="swift">
 
func randBrack(n: Int) -> String {
Line 7,499:
}
 
</syntaxhighlight>output:<syntaxhighlight lang="swift">
 
randBrack(2) // "]][["
 
</syntaxhighlight>Random check balance function:<syntaxhighlight lang="swift">
 
func randIsBal(n: Int) {
Line 7,518:
randIsBal(4)
 
</syntaxhighlight>output:<syntaxhighlight lang="swift">
 
// ][ is unbalanced
Line 7,529:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc generate {n} {
if {!$n} return
set l [lrepeat $n "\[" "\]"]
Line 7,577:
===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:
<syntaxhighlight lang="tcl">proc constructBalancedString {n} {
set s ""
for {set i 0} {$i < $n} {incr i} {
Line 7,591:
 
Generation program in Unix TMG:
<syntaxhighlight lang=UnixTMG"unixtmg">program: readint(n) [n>0] readint(seed)
loop: parse(render) [--n>0?]/done loop;
render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * };
Line 7,619:
 
Analysis can be done easily using grammar specification, rather than counting brackets:
<syntaxhighlight lang=UnixTMG"unixtmg">loop: parse(corr)\loop parse(incorr)\loop;
corr: brkts * = { < OK: > 1 * };
brkts: brkt/null brkts = { 2 1 };
Line 7,642:
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 7,692:
=={{header|TXR}}==
 
<syntaxhighlight lang="txr">@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end)
@(do (defvar r (make-random-state nil))
 
Line 7,751:
== {{header|TypeScript}} ==
{{trans|JavaScript}}
<syntaxhighlight lang="javascript">// Balanced brackets
 
function isStringBalanced(str: string): bool {
Line 7,822:
=={{header|UNIX Shell}}==
{{works with|bash}}
<syntaxhighlight lang="bash">generate() {
local b=()
local i j tmp
Line 7,876:
=={{header|Ursala}}==
 
<syntaxhighlight lang=Ursala"ursala">#import std
#import nat
 
Line 7,903:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Public Function checkBrackets(s As String) As Boolean
'function checks strings for balanced brackets
Line 7,987:
"]][][[[][]]][][[][][": Not OK
</pre>
{{omit from|GUISS}}
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">For n = 1 To 10
sequence = Generate_Sequence(n)
WScript.Echo sequence & " is " & Check_Balance(sequence) & "."
Line 8,042 ⟶ 8,041:
 
Antother version not using libraries. The generator works as intended (more difficult to do than the checking)
<syntaxhighlight lang="vb">
option explicit
 
Line 8,099 ⟶ 8,098:
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Module Module1
 
Private rand As New Random
Line 8,159 ⟶ 8,158:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">import datatypes as dt
 
fn is_valid(bracket string) bool {
Line 8,198 ⟶ 8,197:
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="ecmascript">import "random" for Random
 
var isBalanced = Fn.new { |s|
Line 8,251 ⟶ 8,250:
 
=={{header|X86 Assembly}}==
<syntaxhighlight lang=X86Assembly"x86assembly">
section .data
 
Line 8,323 ⟶ 8,322:
{{trans|JavaScript}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Balanced brackets
PROGRAM "balancedbrackets"
VERSION "0.001"
Line 8,448 ⟶ 8,447:
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">const Chars:[string] = ["[","]"];
func GenerateString(Amount:number=4):string{
set Result:string = "";
Line 8,480 ⟶ 8,479:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes; \intrinsic code declarations
 
int N, I, C, Nest;
Line 8,517 ⟶ 8,516:
 
=={{header|Ya}}==
<syntaxhighlight lang=Ya"ya">@Balanced[]s // each source must be started by specifying its file name; std extension .Ya could be ommitted and auto added by compiler
 
// all types are prefixed by `
Line 8,556 ⟶ 8,555:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub check_brackets(s$)
local level, i
Line 8,576 ⟶ 8,575:
 
=={{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).
<pre>
Line 8,597 ⟶ 8,596:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<syntaxhighlight lang="zxbasic">10 FOR n=1 TO 7
20 READ s$
25 PRINT "The sequence ";s$;" is ";
Line 8,615 ⟶ 8,614:
2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][]["
</syntaxhighlight>
{{omit from|GUISS}}
10,333

edits