new files

This commit is contained in:
Ingy döt Net 2013-04-10 12:38:42 -07:00
parent 3af7344581
commit 86c034bb8b
1364 changed files with 21352 additions and 0 deletions

View file

@ -0,0 +1,10 @@
'''Task''':
* Generate a string with <math>\mathrm{N}</math> opening brackets (“<code>[</code>”) and <math>\mathrm{N}</math> closing brackets (“<code>]</code>”), in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
'''Examples''':
(empty) OK
[] OK ][ NOT OK
[][] OK ][][ NOT OK
[[][]] OK []][[] NOT OK

View file

@ -0,0 +1,21 @@
#!/usr/bin/awk -f
BEGIN {
print isbb("[]")
print isbb("][")
print isbb("][][")
print isbb("[][]")
print isbb("[][][]")
print isbb("[]][[]")
}
function isbb(x) {
s = 0;
for (k=1; k<=length(x); k++) {
c = substr(x,k,1);
if (c=="[") {s++;}
else { if (c=="]") s--; }
if (s<0) {return 0};
}
return (s==0);
}

View file

@ -0,0 +1,57 @@
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Strings.Fixed;
procedure Brackets is
package Random_Positive is new Ada.Numerics.Discrete_Random (Positive);
Positive_Generator : Random_Positive.Generator;
procedure Swap (Left, Right : in out Character) is
Temp : constant Character := Left;
begin
Left := Right;
Right := Temp;
end Swap;
function Generate_Brackets (Bracket_Count : Natural;
Opening_Bracket : Character := '[';
Closing_Bracket : Character := ']')
return String is
use Ada.Strings.Fixed;
All_Brackets : String := Bracket_Count * Opening_Bracket & Bracket_Count * Closing_Bracket;
begin
for I in All_Brackets'Range loop
Swap (All_Brackets (I), All_Brackets (Random_Positive.Random (Positive_Generator) mod (Bracket_Count * 2) + 1));
end loop;
return All_Brackets;
end Generate_Brackets;
function Check_Brackets (Test : String;
Opening_Bracket : Character := '[';
Closing_Bracket : Character := ']')
return Boolean is
Open : Natural := 0;
begin
for I in Test'Range loop
if Test (I) = Opening_Bracket then
Open := Open + 1;
elsif Test (I) = Closing_Bracket then
if Open = 0 then
return False;
else
Open := Open - 1;
end if;
end if;
end loop;
return True;
end Check_Brackets;
begin
Random_Positive.Reset (Positive_Generator);
Ada.Text_IO.Put_Line ("Brackets");
for I in 0 .. 4 loop
for J in 0 .. I loop
declare
My_String : constant String := Generate_Brackets (I);
begin
Ada.Text_IO.Put_Line (My_String & ": " & Boolean'Image (Check_Brackets (My_String)));
end;
end loop;
end loop;
end Brackets;

View file

@ -0,0 +1,57 @@
DECLARE FUNCTION checkBrackets% (brackets AS STRING)
DECLARE FUNCTION generator$ (length AS INTEGER)
RANDOMIZE TIMER
DO
x$ = generator$ (10)
PRINT x$,
IF checkBrackets(x$) THEN
PRINT "OK"
ELSE
PRINT "NOT OK"
END IF
LOOP WHILE LEN(x$)
FUNCTION checkBrackets% (brackets AS STRING)
'returns -1 (TRUE) if everything's ok, 0 (FALSE) if not
DIM L0 AS INTEGER, sum AS INTEGER
FOR L0 = 1 TO LEN(brackets)
SELECT CASE MID$(brackets, L0, 1)
CASE "["
sum = sum + 1
CASE "]"
sum = sum - 1
END SELECT
IF sum < 0 THEN
checkBrackets% = 0
EXIT FUNCTION
END IF
NEXT
IF 0 = sum THEN
checkBrackets% = -1
ELSE
checkBrackets% = 0
END IF
END FUNCTION
FUNCTION generator$ (length AS INTEGER)
z = INT(RND * length)
IF z < 1 THEN generator$ = "": EXIT FUNCTION
REDIM x(z * 2) AS STRING
FOR i = 0 TO z STEP 2
x(i) = "["
x(i + 1) = "]"
NEXT
FOR i = 1 TO UBOUND(x)
z = INT(RND * 2)
IF z THEN SWAP x(i), x(i - 1)
NEXT
xx$ = ""
FOR i = 0 TO UBOUND(x)
xx$ = xx$ + x(i)
NEXT
generator$ = xx$
END FUNCTION

View file

@ -0,0 +1,7 @@
v > "KO TON" ,,,,,, v
> ~ : 25*- #v_ $ | > 25*, @
> "KO" ,, ^
> : 1991+*+- #v_ v
> \ : 1991+*+- #v_v
\ $
^ < <$<

View file

@ -0,0 +1,43 @@
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int isBal(const char*s,int l){
signed c=0;
while(l--)
if(s[l]==']') ++c;
else if(s[l]=='[') if(--c<0) break;
return !c;
}
void shuffle(char*s,int h){
int x,t,i=h;
while(i--){
t=s[x=rand()%h];
s[x]=s[i];
s[i]=t;
}
}
void genSeq(char*s,int n){
if(n){
memset(s,'[',n);
memset(s+n,']',n);
shuffle(s,n*2);
}
s[n*2]=0;
}
void doSeq(int n){
char s[64];
const char *o="False";
genSeq(s,n);
if(isBal(s,n*2)) o="True";
printf("'%s': %s\n",s,o);
}
int main(){
int n=0;
while(n<9) doSeq(n++);
return 0;
}

View file

@ -0,0 +1,9 @@
'': True
'[]': True
']][[': False
'[][][]': True
'[]][[]][': False
'[]][[[[]]]': False
']]]][[[]][[[': False
']]]]]][][[[[[[': False
'[][]][[][[[]]][]': False

View file

@ -0,0 +1,28 @@
(defn gen-brackets [n]
(->> (concat (repeat n \[) (repeat n \]))
shuffle
(apply str ,)))
(defn balanced? [s]
(loop [[first & coll] (seq s)
stack '()]
(if first
(if (= first \[)
(recur coll (conj stack \[))
(when (= (peek stack) \[)
(recur coll (pop stack))))
(zero? (count stack)))))
user> (->> (range 10)
(map gen-brackets ,)
(map (juxt identity balanced?) ,) vec)
[["" true]
["[]" true]
["[[]]" true]
["[][[]]" true]
["[]][][][" nil]
["[[[[[]]]]]" true]
["]][[][][[[]]" nil]
["[]]]][[[[]][][" nil]
["][][[]]][[][][][" nil]
["][][]]][]][[[][[[]" nil]

View file

@ -0,0 +1,15 @@
isBalanced = (brackets) ->
openCount = 0
for bracket in brackets
openCount += if bracket is '[' then 1 else -1
return false if openCount < 0
openCount is 0
bracketsCombinations = (n) ->
for i in [0...Math.pow 2, n]
str = i.toString 2
str = '0' + str while str.length < n
str.replace(/0/g, '[').replace(/1/g, ']')
for brackets in bracketsCombinations 4
console.log brackets, isBalanced brackets

View file

@ -0,0 +1,17 @@
> coffee balanced.coffee
[[[[ false
[[[] false
[[][ false
[[]] true
[][[ false
[][] true
[]][ false
[]]] false
][[[ false
][[] false
][][ false
][]] false
]][[ false
]][] false
]]][ false
]]]] false

View file

@ -0,0 +1,23 @@
include lib/choose.4th ( n1 -- n2)
include lib/ctos.4th ( n -- a 1)
10 constant /[] \ maximum number of brackets
/[] string [] \ string with brackets
\ create string with brackets
: make[] ( --)
0 dup [] place /[] choose 0 ?do 2 choose 2* [char] [ + c>s [] +place loop
; \ empty string, fill with brackets
\ evaluate string
: eval[] ( --)
[] count 2dup over chars + >r swap type 0
begin \ setup string and count
over r@ < \ reached end of string?
while \ if not ..
dup 0< 0= \ unbalanced ]?
while \ if not ..
over c@ [char] \ - negate + swap char+ swap
repeat \ evaluate, goto next character
r> drop if ." NOT" then ." OK" cr drop
; \ evaluate string and print result
make[] eval[]

View file

@ -0,0 +1,55 @@
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func generate(n uint) string {
a := bytes.Repeat([]byte("[]"), int(n))
for i := len(a) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
return string(a)
}
func testBalanced(s string) {
fmt.Printf("%s: ", s)
var open int
for i := 0; i < len(s); i++ {
switch s[i] {
case '[':
open++
case ']':
if open == 0 {
fmt.Println("not ok")
return
}
open--
default:
fmt.Println("not ok")
return
}
}
if open == 0 {
fmt.Println("ok")
} else {
fmt.Println("not ok")
}
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 10; i++ {
testBalanced(generate(i))
}
testBalanced("()")
}

View file

@ -0,0 +1,29 @@
import Control.Monad
import System.Random
import Text.Printf
import VShuffle
-- Return whether a string contains balanced brackets. Nothing indicates a
-- balanced string, while (Just i) means an imbalance was found at, or just
-- after, the i'th bracket. We assume the string contains only brackets.
isBalanced :: String -> Maybe Int
isBalanced = bal (-1) 0
where bal :: Int -> Int -> String -> Maybe Int
bal _ 0 [] = Nothing
bal i _ [] = Just i
bal i (-1) _ = Just i
bal i n ('[':bs) = bal (i+1) (n+1) bs
bal i n (']':bs) = bal (i+1) (n-1) bs
-- Print a string, indicating whether it contains balanced brackets. If not,
-- indicate the bracket at which the imbalance was found.
check :: String -> IO ()
check s = maybe (good s) (bad s) (isBalanced s)
where good s = printf "Good \"%s\"\n" s
bad s n = printf "Bad \"%s\"\n%*s^\n" s (n+6) " "
main :: IO ()
main = do
let bs = cycle "[]"
rs <- replicateM 10 newStdGen
zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2..] rs

View file

@ -0,0 +1,20 @@
module VShuffle (shuffle) where
import Data.List (mapAccumL)
import System.Random
import Control.Monad.ST
import qualified Data.Vector as V
import qualified Data.Vector.Generic.Mutable as M
-- Generate a list of array index pairs, each corresponding to a swap.
pairs :: (Enum a, Random a, RandomGen g) => a -> a -> g -> [(a, a)]
pairs l u r = snd $ mapAccumL step r [l..pred u]
where step r i = let (j, r') = randomR (i, u) r in (r', (i, j))
-- Return a random permutation of the list. We use the algorithm described in
-- http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm.
shuffle :: (RandomGen g) => [a] -> g -> [a]
shuffle xs r = V.toList . runST $ do
v <- V.unsafeThaw $ V.fromList xs
mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r
V.unsafeFreeze v

View file

@ -0,0 +1,50 @@
public class Brackets {
public static boolean checkBrackets(String str){
int mismatchedBrackets = 0;
for(char ch:str.toCharArray()){
if(ch == '['){
mismatchedBrackets++;
}else if(ch == ']'){
mismatchedBrackets--;
}else{
return false; //non-bracket chars
}
if(mismatchedBrackets < 0){ //close bracket before open bracket
return false;
}
}
return mismatchedBrackets == 0;
}
public static String generate(int n){
if(n % 2 == 1){ //if n is odd we can't match brackets
return null;
}
String ans = "";
int openBracketsLeft = n / 2;
int unclosed = 0;
while(ans.length() < n){
if(Math.random() >= .5 && openBracketsLeft > 0 || unclosed == 0){
ans += '[';
openBracketsLeft--;
unclosed++;
}else{
ans += ']';
unclosed--;
}
}
return ans;
}
public static void main(String[] args){
String[] tests = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"};
for(int i = 0; i <= 16; i+=2){
String bracks = generate(i);
System.out.println(bracks + ": " + checkBrackets(bracks));
}
for(String test: tests){
System.out.println(test + ": " + checkBrackets(test));
}
}
}

View file

@ -0,0 +1,43 @@
function createRandomBracketSequence(maxlen)
{
var chars = { '0' : '[' , '1' : ']' };
function getRandomInteger(to)
{
return Math.floor(Math.random() * (to+1));
}
var n = getRandomInteger(maxlen);
var result = [];
for(var i = 0; i < n; i++)
{
result.push(chars[getRandomInteger(1)]);
}
return result.join("");
}
function bracketsAreBalanced(s)
{
var open = (arguments.length > 1) ? arguments[1] : '[';
var close = (arguments.length > 2) ? arguments[2] : ']';
var c = 0;
for(var i = 0; i < s.length; i++)
{
var ch = s.charAt(i);
if ( ch == open )
{
c++;
}
else if ( ch == close )
{
c--;
if ( c < 0 ) return false;
}
}
return c == 0;
}
var c = 0;
while ( c < 5 ) {
var seq = createRandomBracketSequence(8);
alert(seq + ':\t' + bracketsAreBalanced(seq));
c++;
}

View file

@ -0,0 +1,29 @@
function checkBalance(i) {
while (i.length % 2 == 0) {
j = i.replace('{}','');
if (j == i)
break;
i = j;
}
return (i?false:true);
}
var g = 10;
while (g--) {
var N = 10 - Math.floor(g/2), n=N, o='';
while (n || N) {
if (N == 0 || n == 0) {
o+=Array(++N).join('}') + Array(++n).join('{');
break;
}
if (Math.round(Math.random()) == 1) {
o+='}';
N--;
}
else {
o+='{';
n--;
}
}
alert(o+": "+checkBalance(o));
}

View file

@ -0,0 +1,20 @@
function isBalanced(s)
--Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.
--Any two characters can be used.
return s:gsub('%b[]','')=='' and true or false
end
function randomString()
math.randomseed(os.time())
math.random()math.random()math.random()math.random()
local tokens={'[',']'}
local result={}
for i=1,8 do
table.insert(result,tokens[math.random(1,2)])
end
return table.concat(result)
end
local RS=randomString()
print(RS)
print(isBalanced(RS))

View file

@ -0,0 +1,13 @@
use 5.10.0; # for given ... when construct
sub balanced {
my $depth = 0;
for (split //, shift) {
when('[') { ++$depth }
when(']') { return if --$depth < 0 }
}
return !$depth
}
for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "" : "not ", "balanced:\t'$_'\n";
}

View file

@ -0,0 +1,10 @@
use 5.10.0; # for '++' non-backtrack behavior
sub balanced {
my $_ = shift;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
! /[\[\]]/;
}
for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "" : "not ", "balanced:\t'$_'\n";
}

View file

@ -0,0 +1,17 @@
(load "@lib/simul.l") # For 'shuffle'
(de generateBrackets (N)
(shuffle (make (do N (link "[" "]")))) )
(de checkBrackets (S)
(let N 0
(for C S
(if (= C "[")
(inc 'N)
(if2 (= C "]") (=0 N)
(off N)
(dec 'N) ) ) )
(=0 N) ) )
(for N 10
(prinl (if (checkBrackets (prin (generateBrackets N))) " OK" "not OK")) )

View file

@ -0,0 +1,52 @@
rosetta_brackets :-
test_brackets([]),
test_brackets(['[',']']),
test_brackets(['[',']','[',']']),
test_brackets(['[','[',']','[',']',']']),
test_brackets([']','[']),
test_brackets([']','[',']','[']),
test_brackets(['[',']',']','[','[',']']).
balanced_brackets :-
gen_bracket(2, B1, []), test_brackets(B1),
gen_bracket(4, B2, []), test_brackets(B2),
gen_bracket(4, B3, []), test_brackets(B3),
gen_bracket(6, B4, []), test_brackets(B4),
gen_bracket(6, B5, []), test_brackets(B5),
gen_bracket(8, B6, []), test_brackets(B6),
gen_bracket(8, B7, []), test_brackets(B7),
gen_bracket(10, B8, []), test_brackets(B8),
gen_bracket(10, B9, []), test_brackets(B9).
test_brackets(Goal) :-
( Goal = [] -> write('(empty)'); maplist(write, Goal)),
( balanced_brackets(Goal, []) ->
writeln(' succeed')
;
writeln(' failed')
).
% grammar of balanced brackets
balanced_brackets --> [].
balanced_brackets -->
['['],
balanced_brackets,
[']'].
balanced_brackets -->
['[',']'],
balanced_brackets.
% generator of random brackets
gen_bracket(0) --> [].
gen_bracket(N) -->
{N1 is N - 1,
R is random(2)},
bracket(R),
gen_bracket(N1).
bracket(0) --> ['['].
bracket(1) --> [']'].

View file

@ -0,0 +1,27 @@
>>> def gen(N):
... txt = ['[', ']'] * N
... random.shuffle( txt )
... return ''.join(txt)
...
>>> def balanced(txt):
... braced = 0
... for ch in txt:
... if ch == '[': braced += 1
... if ch == ']':
... braced -= 1
... if braced < 0: return False
... return braced == 0
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'[]' is balanced
'[][]' is balanced
'][[[]]' is not balanced
'[]][[][]' is not balanced
'[][[][]]][' is not balanced
'][]][][[]][[' is not balanced
'[[]]]]][]][[[[' is not balanced
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced

View file

@ -0,0 +1,5 @@
balanced <- function(str){
str <- strsplit(str, "")[[1]]
str <- ifelse(str=='[', 1, -1)
all(cumsum(str) >= 0) && sum(str) == 0
}

View file

@ -0,0 +1,3 @@
balanced <- function(str) {
regexpr('^(\\[(?1)*\\])*$', str, perl=TRUE) > -1
}

View file

@ -0,0 +1,6 @@
rand.parens <- function(n) paste(permute(c(rep('[',n),rep(']',n))),collapse="")
as.data.frame(within(list(), {
parens <- replicate(10, rand.parens(sample.int(10,size=1)))
balanced <- sapply(parens, balanced)
}))

View file

@ -0,0 +1,11 @@
balanced parens
1 FALSE ][][
2 FALSE [][[]]][[]][]]][[[
3 FALSE ][[][][]][][[]
4 FALSE ][][][][][][][
5 TRUE [[[][]]][[[][][]]]
6 TRUE []
7 FALSE ]][[][[]
8 FALSE []]]][[[]][[[]
9 TRUE [[[[][[][]]]]]
10 TRUE []

View file

@ -0,0 +1,40 @@
/*REXX program to check for balanced brackets [] */
@.=0
yesno.0 = left('',40) 'unbalanced'
yesno.1 = 'balanced'
q='[][][][[]]' ; call checkBal q; say yesno.result q
q='[][][][[]]][' ; call checkBal q; say yesno.result q
q='[' ; call checkBal q; say yesno.result q
q=']' ; call checkBal q; say yesno.result q
q='[]' ; call checkBal q; say yesno.result q
q='][' ; call checkBal q; say yesno.result q
q='][][' ; call checkBal q; say yesno.result q
q='[[]]' ; call checkBal q; say yesno.result q
q='[[[[[[[]]]]]]]' ; call checkBal q; say yesno.result q
q='[[[[[]]]][]' ; call checkBal q; say yesno.result q
q='[][]' ; call checkBal q; say yesno.result q
q='[]][[]' ; call checkBal q; say yesno.result q
q=']]][[[[]' ; call checkBal q; say yesno.result q
do j=1 for 40
q=translate(rand(random(1,8)),'[]',01)
call checkBal q; if result=='-1' then iterate
say yesno.result q
end
exit
/*───────────────────────────────────PAND subroutine────────────────────*/
pand: p=random(0,1); return p || \p
/*───────────────────────────────────RAND subroutine────────────────────*/
rand: pp=pand(); pp=pand()pp; pp=copies(pp,arg(1))
i=random(2,length(pp)); pp=left(pp,i-1)substr(pp,i)
return pp
/*───────────────────────────────────CHECKBAL subroutine────────────────*/
checkBal: procedure expose @.; arg y /*check for balanced brackets [] */
nest=0; if @.y then return '-1' /*already done this expression ? */
@.y=1 /*indicate expression processed. */
do j=1 for length(y); _=substr(y,j,1) /*pick off character.*/
if _=='[' then nest=nest+1
else do; nest=nest-1; if nest<0 then return 0; end
end /*j*/
return nest==0

View file

@ -0,0 +1,67 @@
/*REXX program to check for balanced brackets [] **********************
* test strings and random string generation copied from Version 1
* the rest restructured (shortened) to some extent
* and output made reproducible (random with a seed)
* 10.07.2012 Walter Pachl
**********************************************************************/
yesno.0 = 'unbalanced'
yesno.1 = ' balanced'
done.=0 /* memory what's been done */
n=0 /* number of tests */
Call testbal '[][][][[]]' /* first some user written tests */
Call testbal '[][][][[]]]['
Call testbal '['
Call testbal ']'
Call testbal '[]'
Call testbal ']['
Call testbal '][]['
Call testbal '[[]]'
Call testbal '[[[[[[[]]]]]]]'
Call testbal '[[[[[]]]][]'
Call testbal '[][]'
Call testbal '[]][[]'
Call testbal ']]][[[[]'
Call testbal ']'
Call testbal '['
/* then some random generated ones */
Call random 1,2,12345 /* call random with a seed */
/* makes test reproducible */
do Until n=30 /* up to 30 tests */
s=rand(random(1,8)) /* a 01 etc. string of length 4-32 */
q=translate(s,'[]',01) /* turn digits into brackets */
if done.q then /* string was already here */
iterate /* don't test again */
call testbal q /* test balance */
End
exit
testbal: /* test the given string and show result */
n=n+1 /* number of tests */
Parse Arg q /* get string to be tested */
done.q=1 /* mark as done */
call checkBal q /* test balance */
lq=format(length(q),2)
say right(n,2) lq yesno.result q/* show result and string */
Return
/*-----------------------------------PAND subroutine-----------------*/
pand: p=random(0,1); return p || \p
/*-----------------------------------RAND subroutine-----------------*/
rand: pp=pand(); pp=pand()pp; pp=copies(pp,arg(1))
i=random(2,length(pp)); pp=left(pp,i-1)substr(pp,i)
return pp
checkBal: procedure /*check for balanced brackets () */
Parse arg y
nest=0;
do While y<>''
Parse Var y c +1 y /*pick off one character at a time */
if c='[' then /* opening bracket */
nest=nest+1 /* increment nesting */
else do /* closing bracket */
if nest=0 then /* not allowed */
return 0; /* no success */
nest=nest-1 /* decrement nesting */
end
end
return nest=0 /* nest=0 -> balanced */

View file

@ -0,0 +1,58 @@
/*REXX program to check for balanced brackets [ ] */
count=0
nested=0
yesno.0 = left('',40) 'unbalanced'
yesno.1 = 'balanced'
q='' ; call checkBal q; say yesno.result q
q='[][][][[]]' ; call checkBal q; say yesno.result q
q='[][][][[]]][' ; call checkBal q; say yesno.result q
q='[' ; call checkBal q; say yesno.result q
q=']' ; call checkBal q; say yesno.result q
q='[]' ; call checkBal q; say yesno.result q
q='][' ; call checkBal q; say yesno.result q
q='][][' ; call checkBal q; say yesno.result q
q='[[]]' ; call checkBal q; say yesno.result q
q='[[[[[[[]]]]]]]' ; call checkBal q; say yesno.result q
q='[[[[[]]]][]' ; call checkBal q; say yesno.result q
q='[][]' ; call checkBal q; say yesno.result q
q='[]][[]' ; call checkBal q; say yesno.result q
q=']]][[[[]' ; call checkBal q; say yesno.result q
call teller
count=0
nested=0
do j=1 /*generate lots of permutations. */
q=translate(strip(x2b(d2x(j)),'L',0),"][",01) /*convert──►[].*/
if countstr(']',q)\==countstr('[',q) then iterate /*compliant?*/
call checkBal q
if length(q)>20 then leave /*done all 20-char possibilities?*/
end
/*───────────────────────────────────TELLER subroutine──────────────────*/
teller: say
say count " expressions were checked, " nested ' were balanced, ',
count-nested " were unbalanced."
return
/*───────────────────────────────────CHECKBAL subroutine────────────────*/
checkBal: procedure expose nested count; parse arg y; count=count+1
nest=0
do j=1 for length(y); _=substr(y,j,1) /*pick off character.*/
select
when _=='[' then nest=nest+1 /*opening bracket ...*/
when _==']' then do; nest=nest-1; if nest<0 then leave; end
otherwise nop /*ignore any chaff. */
end /*select*/
end /*j*/
nested=nested + (nest==0)
return nest==0
/* ┌──────────────────────────────────────────────────────────────────┐
COUNTSTR counts the number of occurances of a string (or char)
within another string (haystack) without overlap. If either arg
is null, 0 (zero) is returned. To make the subroutine case
insensative, change the PARSE ARG ... statement to ARG ...
Example: yyy = 'The quick brown fox jumped over the lazy dog.'
zz = countstr('o',yyy) /*ZZ will be set to 4 */
Note that COUNTSTR is also a built-in function of the newer
REXX interpreters, and the result should be identical. Checks
could be added to validate if 2 or 3 arguments are passed.
*/
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

View file

@ -0,0 +1,17 @@
#lang racket
(define (generate n)
(list->string (shuffle (append* (make-list n '(#\[ #\]))))))
(define (balanced? str)
(let loop ([l (string->list str)] [n 0])
(or (null? l)
(if (eq? #\[ (car l))
(loop (cdr l) (add1 n))
(and (> n 0) (loop (cdr l) (sub1 n)))))))
(define (try n)
(define s (generate n))
(printf "~a => ~a\n" s (if (balanced? s) "OK" "NOT OK")))
(for ([n 10]) (try n))

View file

@ -0,0 +1,24 @@
re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
\g<bb>* # zero or more <bb>
\] # literal ]
)* # end group, zero or more such groups
\z/x # end of string
(0..9).each do |i|
s = "[]" * i
# There is no String#shuffle! method.
# This is a Knuth shuffle.
(s.length - 1).downto(1) do |a; b|
b = rand(a + 1)
s[a], s[b] = s[b], s[a]
end
puts((s =~ re ? " OK: " : "bad: ") + s)
end
["[[]", "[]]", "[letters]"].each do |s|
puts((s =~ re ? " OK: " : "bad: ") + s)
end

View file

@ -0,0 +1,36 @@
import scala.collection.mutable.ListBuffer
import scala.util.Random
object BalancedBrackets extends App {
val random = new Random()
def generateRandom: List[String] = {
import scala.util.Random._
val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_)
(1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList
}
def generate(n: Int): List[String] = {
val base = "["*n+"]"*n
var lb = ListBuffer[String]()
base.permutations.foreach(s=>lb+=s)
lb.toList.sorted
}
def checkBalance(brackets: String):Boolean = {
def balI(brackets: String, depth: Int):Boolean = {
if (brackets == "") depth == 0
else brackets(0) match {
case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1))
case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1))
case _ => false
}
}
balI(brackets, 0)
}
println("arbitrary random order:")
generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
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))
}

View file

@ -0,0 +1,23 @@
(define (balanced-brackets string)
(define (b chars sum)
(cond ((and (null? chars) (= 0 sum))
#t)
((null? chars)
#f)
((char=? #\[ (car chars))
(b (cdr chars) (+ sum 1)))
((= sum 0)
#f)
(else
(b (cdr chars) (- sum 1)))))
(b (string->list string) 0))
(balanced-brackets "")
(balanced-brackets "[]")
(balanced-brackets "[][]")
(balanced-brackets "[[][]]")
(balanced-brackets "][")
(balanced-brackets "][][")
(balanced-brackets "[]][[]")

View file

@ -0,0 +1,28 @@
proc generate {n} {
if {!$n} return
set l [lrepeat $n "\[" "\]"]
set len [llength $l]
while {$len} {
set tmp [lindex $l [set i [expr {int($len * rand())}]]]
lset l $i [lindex $l [incr len -1]]
lset l $len $tmp
}
return [join $l ""]
}
proc balanced s {
set n 0
foreach c [split $s ""] {
# Everything unmatched is ignored, which is what we want
switch -exact -- $c {
"\[" {incr n}
"\]" {if {[incr n -1] < 0} {return false}}
}
}
expr {!$n}
}
for {set i 0} {$i < 15} {incr i} {
set s [generate $i]
puts "\"$s\"\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]"
}

View file

@ -0,0 +1,8 @@
proc constructBalancedString {n} {
set s ""
for {set i 0} {$i < $n} {incr i} {
set x [expr {int(rand() * ([string length $s] + 1))}]
set s "[string range $s 0 [expr {$x-1}]]\[\][string range $s $x end]"
}
return $s
}