2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -1,10 +1,12 @@
|
|||
'''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.
|
||||
* Generate a string with '''N''' opening brackets <big>'''['''</big> and with '''N''' closing brackets <big>''']'''</big>, 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''':
|
||||
|
||||
|
||||
;Examples:
|
||||
(empty) OK
|
||||
[] OK ][ NOT OK
|
||||
[][] OK ][][ NOT OK
|
||||
[[][]] OK []][[] NOT OK
|
||||
<br><br>
|
||||
|
|
|
|||
101
Task/Balanced-brackets/360-Assembly/balanced-brackets.360
Normal file
101
Task/Balanced-brackets/360-Assembly/balanced-brackets.360
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
* Balanced brackets 28/04/2016
|
||||
BALANCE CSECT
|
||||
USING BALANCE,R13 base register and savearea pointer
|
||||
SAVEAREA B STM-SAVEAREA(R15)
|
||||
DC 17F'0'
|
||||
STM STM R14,R12,12(R13)
|
||||
ST R13,4(R15)
|
||||
ST R15,8(R13)
|
||||
LR R13,R15 establish addressability
|
||||
LA R8,1 i=1
|
||||
LOOPI C R8,=F'20' do i=1 to 20
|
||||
BH ELOOPI
|
||||
MVC C(20),=CL20' ' c=' '
|
||||
LA R1,1
|
||||
LA R2,10
|
||||
BAL R14,RANDOMX
|
||||
LR R11,R0 l=randomx(1,10)
|
||||
SLA R11,1 l=l*2
|
||||
LA R10,1 j=1
|
||||
LOOPJ CR R10,R11 do j=1 to 2*l
|
||||
BH ELOOPJ
|
||||
LA R1,0
|
||||
LA R2,1
|
||||
BAL R14,RANDOMX
|
||||
LR R12,R0 m=randomx(0,1)
|
||||
LTR R12,R12 if m=0
|
||||
BNZ ELSEM
|
||||
MVI Q,C'[' q='['
|
||||
B EIFM
|
||||
ELSEM MVI Q,C']' q=']'
|
||||
EIFM LA R14,C-1(R10) @c(j)
|
||||
MVC 0(1,R14),Q c(j)=q
|
||||
LA R10,1(R10) j=j+1
|
||||
B LOOPJ
|
||||
ELOOPJ BAL R14,CHECKBAL
|
||||
LR R2,R0
|
||||
C R2,=F'1' if checkbal=1
|
||||
BNE ELSEC
|
||||
MVC PG+24(2),=C'ok' rep='ok'
|
||||
B EIFC
|
||||
ELSEC MVC PG+24(2),=C'? ' rep='? '
|
||||
EIFC XDECO R8,XDEC i
|
||||
MVC PG+0(2),XDEC+10
|
||||
MVC PG+3(20),C
|
||||
XPRNT PG,26
|
||||
LA R8,1(R8) i=i+1
|
||||
B LOOPI
|
||||
ELOOPI L R13,4(0,R13)
|
||||
LM R14,R12,12(R13)
|
||||
XR R15,R15 set return code to 0
|
||||
BR R14 -------------- end
|
||||
CHECKBAL CNOP 0,4 -------------- checkbal
|
||||
SR R6,R6 n=0
|
||||
LA R7,1 k=1
|
||||
LOOPK C R7,=F'20' do k=1 to 20
|
||||
BH ELOOPK
|
||||
LR R1,R7 k
|
||||
LA R4,C-1(R1) @c(k)
|
||||
MVC CI(1),0(R4) ci=c(k)
|
||||
CLI CI,C'[' if ci='['
|
||||
BNE NOT1
|
||||
LA R6,1(R6) n=n+1
|
||||
NOT1 CLI CI,C']' if ci=']'
|
||||
BNE NOT2
|
||||
BCTR R6,0 n=n-1
|
||||
NOT2 LTR R6,R6 if n<0
|
||||
BNM NSUP0
|
||||
SR R0,R0 return(0)
|
||||
B RETCHECK
|
||||
NSUP0 LA R7,1(R7) k=k+1
|
||||
B LOOPK
|
||||
ELOOPK LTR R6,R6 if n=0
|
||||
BNZ ELSEN
|
||||
LA R0,1 return(1)
|
||||
B RETCHECK
|
||||
ELSEN SR R0,R0 return(0)
|
||||
RETCHECK BR R14 -------------- end checkbal
|
||||
RANDOMX CNOP 0,4 -------------- randomx
|
||||
LR R3,R2 i2
|
||||
SR R3,R1 ii=i2-i1
|
||||
L R5,SEED
|
||||
M R4,=F'1103515245'
|
||||
A R5,=F'12345'
|
||||
SRDL R4,1 shift to improve the algorithm
|
||||
ST R5,SEED seed=(seed*1103515245+12345)>>1
|
||||
LR R6,R3 ii
|
||||
LA R6,1(R6) ii+1
|
||||
L R5,SEED seed
|
||||
LA R4,0 clear
|
||||
DR R4,R6 seed//(ii+1)
|
||||
AR R4,R1 +i1
|
||||
LR R0,R4 return(seed//(ii+1)+i1)
|
||||
BR R14 -------------- end randomx
|
||||
SEED DC F'903313037'
|
||||
C DS 20CL1
|
||||
Q DS CL1
|
||||
CI DS CL1
|
||||
PG DC CL80' '
|
||||
XDEC DS CL12
|
||||
REGS
|
||||
END BALANCE
|
||||
188
Task/Balanced-brackets/AppleScript/balanced-brackets.applescript
Normal file
188
Task/Balanced-brackets/AppleScript/balanced-brackets.applescript
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
-- CHECK NESTING OF SQUARE BRACKET SEQUENCES
|
||||
|
||||
-- Zero-based index of the first problem (-1 if none found):
|
||||
|
||||
-- imbalance :: String -> Integer
|
||||
on imbalance(strBrackets)
|
||||
script
|
||||
on errorIndex(xs, iDepth, iIndex)
|
||||
set lngChars to length of xs
|
||||
if lngChars > 0 then
|
||||
set iNext to iDepth + cond(item 1 of xs = "[", 1, -1)
|
||||
|
||||
if iNext < 0 then -- closing bracket unmatched
|
||||
iIndex
|
||||
else
|
||||
if lngChars > 1 then -- continue recursively
|
||||
errorIndex(items 2 thru -1 of xs, iNext, iIndex + 1)
|
||||
else -- end of string
|
||||
cond(iNext = 0, -1, iIndex)
|
||||
end if
|
||||
end if
|
||||
else
|
||||
cond(iDepth = 0, -1, iIndex)
|
||||
end if
|
||||
end errorIndex
|
||||
end script
|
||||
|
||||
result's errorIndex(characters of strBrackets, 0, 0)
|
||||
end imbalance
|
||||
|
||||
|
||||
|
||||
-- TEST
|
||||
|
||||
-- Random bracket sequences for testing
|
||||
-- brackets :: Int -> String
|
||||
on brackets(n)
|
||||
-- bracket :: () -> String
|
||||
script bracket
|
||||
on lambda(_)
|
||||
cond((random number) < 0.5, "[", "]")
|
||||
end lambda
|
||||
end script
|
||||
intercalate("", map(bracket, range(1, n)))
|
||||
end brackets
|
||||
|
||||
on run
|
||||
set nPairs to 6
|
||||
|
||||
-- report :: Int -> String
|
||||
script report
|
||||
property strPad : concatReplicate(nPairs * 2 + 4, space)
|
||||
|
||||
on lambda(n)
|
||||
set w to n * 2
|
||||
set s to brackets(w)
|
||||
set i to imbalance(s)
|
||||
set blnOK to (i = -1)
|
||||
|
||||
set strStatus to cond(blnOK, "OK", "problem")
|
||||
|
||||
set strLine to "'" & s & "'" & ¬
|
||||
(items (w + 2) thru -1 of strPad) & strStatus
|
||||
|
||||
set strPointer to cond(blnOK, "", linefeed & concatReplicate(i + 1, space) & "^")
|
||||
|
||||
intercalate("", {strLine, strPointer})
|
||||
end lambda
|
||||
end script
|
||||
|
||||
linefeed & ¬
|
||||
intercalate(linefeed, ¬
|
||||
map(report, range(0, nPairs))) & linefeed
|
||||
end run
|
||||
|
||||
|
||||
-- GENERIC LIBRARY FUNCTIONS
|
||||
|
||||
-- map :: (a -> b) -> [a] -> [b]
|
||||
on map(f, xs)
|
||||
tell mReturn(f)
|
||||
set lng to length of xs
|
||||
set lst to {}
|
||||
repeat with i from 1 to lng
|
||||
set end of lst to lambda(item i of xs, i, xs)
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end map
|
||||
|
||||
-- foldl :: (a -> b -> a) -> a -> [b] -> a
|
||||
on foldl(f, startValue, xs)
|
||||
tell mReturn(f)
|
||||
set v to startValue
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to lambda(v, item i of xs, i, xs)
|
||||
end repeat
|
||||
return v
|
||||
end tell
|
||||
end foldl
|
||||
|
||||
-- Text -> [Text] -> Text
|
||||
on intercalate(strText, lstText)
|
||||
set {dlm, my text item delimiters} to {my text item delimiters, strText}
|
||||
set strJoined to lstText as text
|
||||
set my text item delimiters to dlm
|
||||
return strJoined
|
||||
end intercalate
|
||||
|
||||
-- concatReplicate :: Int -> String -> String
|
||||
on concatReplicate(n, s)
|
||||
concat(replicate(n, s))
|
||||
end concatReplicate
|
||||
|
||||
-- Egyptian multiplication - progressively doubling a list, appending
|
||||
-- stages of doubling to an accumulator where needed for binary
|
||||
-- assembly of a target length
|
||||
|
||||
-- replicate :: Int -> a -> [a]
|
||||
on replicate(n, a)
|
||||
set out to {}
|
||||
if n < 1 then return out
|
||||
set dbl to {a}
|
||||
|
||||
repeat while (n > 1)
|
||||
if (n mod 2) > 0 then set out to out & dbl
|
||||
set n to (n div 2)
|
||||
set dbl to (dbl & dbl)
|
||||
end repeat
|
||||
return out & dbl
|
||||
end replicate
|
||||
|
||||
-- concat :: [[a]] -> [a] | [String] -> String
|
||||
on concat(xs)
|
||||
script append
|
||||
on lambda(a, b)
|
||||
a & b
|
||||
end lambda
|
||||
end script
|
||||
|
||||
if length of xs > 0 and class of (item 1 of xs) is string then
|
||||
foldl(append, "", xs)
|
||||
else
|
||||
foldl(append, {}, xs)
|
||||
end if
|
||||
end concat
|
||||
|
||||
-- Value of one of two expressions
|
||||
-- cond :: Bool -> a -> b -> c
|
||||
on cond(bln, f, g)
|
||||
if bln then
|
||||
set e to f
|
||||
else
|
||||
set e to g
|
||||
end if
|
||||
if class of e is handler then
|
||||
mReturn(e)'s lambda()
|
||||
else
|
||||
e
|
||||
end if
|
||||
end cond
|
||||
|
||||
-- range :: Int -> Int -> [Int]
|
||||
on range(m, n)
|
||||
if n < m then
|
||||
set d to -1
|
||||
else
|
||||
set d to 1
|
||||
end if
|
||||
set lst to {}
|
||||
repeat with i from m to n by d
|
||||
set end of lst to i
|
||||
end repeat
|
||||
return lst
|
||||
end range
|
||||
|
||||
-- Lift 2nd class handler function into 1st class script wrapper
|
||||
-- mReturn :: Handler -> Script
|
||||
on mReturn(f)
|
||||
if class of f is script then
|
||||
f
|
||||
else
|
||||
script
|
||||
property lambda : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
|
@ -1,23 +1,20 @@
|
|||
defmodule Balanced_brackets do
|
||||
def task do
|
||||
Enum.each(0..5, fn n ->
|
||||
string = generate(n)
|
||||
result = is_balanced(string) |> task_balanced
|
||||
IO.puts "#{string} is #{result}"
|
||||
brackets = generate(n)
|
||||
result = is_balanced(brackets) |> task_balanced
|
||||
IO.puts "#{brackets} is #{result}"
|
||||
end)
|
||||
end
|
||||
|
||||
def generate( 0 ), do: []
|
||||
def generate( n ) do
|
||||
for _ <- 1..2*n, do: generate_bracket(:rand.uniform(2))
|
||||
defp generate( 0 ), do: []
|
||||
defp generate( n ) do
|
||||
for _ <- 1..2*n, do: Enum.random ["[", "]"]
|
||||
end
|
||||
|
||||
defp generate_bracket( 1 ), do: "["
|
||||
defp generate_bracket( 2 ), do: "]"
|
||||
def is_balanced( brackets ), do: is_balanced_loop( brackets, 0 )
|
||||
|
||||
def is_balanced( string ), do: is_balanced_loop( string, 0 )
|
||||
|
||||
defp is_balanced_loop( _string, n ) when n < 0, do: false
|
||||
defp is_balanced_loop( _, n ) when n < 0, do: false
|
||||
defp is_balanced_loop( [], 0 ), do: true
|
||||
defp is_balanced_loop( [], _n ), do: false
|
||||
defp is_balanced_loop( ["[" | t], n ), do: is_balanced_loop( t, n + 1 )
|
||||
|
|
|
|||
|
|
@ -1,43 +1,17 @@
|
|||
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 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
|
||||
return a.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;
|
||||
function isBalanced(str) {
|
||||
var a = str, b
|
||||
do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
|
||||
return !a
|
||||
}
|
||||
|
||||
var c = 0;
|
||||
while ( c < 5 ) {
|
||||
var seq = createRandomBracketSequence(8);
|
||||
alert(seq + ':\t' + bracketsAreBalanced(seq));
|
||||
c++;
|
||||
var M = 20
|
||||
while (M-- > 0) {
|
||||
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
|
||||
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +1,60 @@
|
|||
function checkBalance(i) {
|
||||
while (i.length % 2 == 0) {
|
||||
j = i.replace('{}','');
|
||||
if (j == i)
|
||||
break;
|
||||
i = j;
|
||||
}
|
||||
return (i?false:true);
|
||||
}
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
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));
|
||||
}
|
||||
// Int -> String
|
||||
let randomBrackets = n => range(1, n)
|
||||
.map(() => Math.random() < 0.5 ? '[' : ']')
|
||||
.join('');
|
||||
|
||||
// imbalance :: String -> Integer
|
||||
let imbalance = strBrackets => {
|
||||
|
||||
// iDepth: initial nesting depth (0 = closed)
|
||||
// iIndex: starting character position
|
||||
|
||||
// errorIndex :: [Char] -> Int -> Int -> Int
|
||||
let errorIndex = (xs, iDepth, iIndex) => {
|
||||
if (xs.length > 0) {
|
||||
let tail = xs.slice(1),
|
||||
iNext = iDepth + (xs[0] === '[' ? 1 : -1);
|
||||
|
||||
if (iNext < 0) return iIndex; // unmatched closing bracket
|
||||
else return tail.length ? errorIndex(
|
||||
tail, iNext, iIndex + 1
|
||||
) : iNext === 0 ? -1 : iIndex; // balanced ? problem index ?
|
||||
|
||||
} else return iDepth === 0 ? -1 : iIndex;
|
||||
};
|
||||
|
||||
return errorIndex(strBrackets.split(''), 0, 0);
|
||||
};
|
||||
|
||||
|
||||
// GENERIC FUNCTION
|
||||
|
||||
// range :: Int -> Int -> [Int]
|
||||
let range = (m, n) =>
|
||||
Array.from({
|
||||
length: Math.floor(n - m) + 1
|
||||
}, (_, i) => m + i);
|
||||
|
||||
// TESTING AND FORMATTING OUTPUT
|
||||
|
||||
let lngPairs = 6,
|
||||
strPad = Array(lngPairs * 2 + 4)
|
||||
.join(' ');
|
||||
|
||||
return range(0, lngPairs)
|
||||
.map(n => {
|
||||
let w = n * 2,
|
||||
s = randomBrackets(w),
|
||||
i = imbalance(s),
|
||||
blnOK = i === -1;
|
||||
|
||||
return "'" + s + "'" + strPad.slice(w + 2) +
|
||||
(blnOK ? 'OK' : 'problem') +
|
||||
(blnOK ? '' : '\n' + Array(i + 2)
|
||||
.join(' ') + '^');
|
||||
})
|
||||
.join('\n');
|
||||
})();
|
||||
|
|
|
|||
14
Task/Balanced-brackets/K/balanced-brackets.k
Normal file
14
Task/Balanced-brackets/K/balanced-brackets.k
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
gen_brackets:{"[]"@x _draw 2}
|
||||
check:{r:(-1;1)@"["=x; *(0=+/cs<'0)&(0=-1#cs:+\r)}
|
||||
|
||||
{(x;check x)}' gen_brackets' 2*1+!10
|
||||
(("[[";0)
|
||||
("[][]";1)
|
||||
("][][]]";0)
|
||||
("[[][[][]";0)
|
||||
("][]][[[[[[";0)
|
||||
("]]][[]][]]][";0)
|
||||
("[[[]][[[][[[][";0)
|
||||
("[[]][[[]][]][][]";1)
|
||||
("][[][[]]][[]]]][][";0)
|
||||
("]][[[[]]]][][][[]]]]";0))
|
||||
102
Task/Balanced-brackets/Oberon-2/balanced-brackets.oberon-2
Normal file
102
Task/Balanced-brackets/Oberon-2/balanced-brackets.oberon-2
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
MODULE BalancedBrackets;
|
||||
IMPORT
|
||||
Object,
|
||||
Object:Boxed,
|
||||
ADT:LinkedList,
|
||||
ADT:Storable,
|
||||
IO,
|
||||
Out := NPCT:Console;
|
||||
|
||||
TYPE
|
||||
(* CHAR is not boxed in the standard lib *)
|
||||
(* so make a boxed char *)
|
||||
Character* = POINTER TO CharacterDesc;
|
||||
CharacterDesc* = RECORD
|
||||
(Boxed.ObjectDesc)
|
||||
c: CHAR;
|
||||
END;
|
||||
|
||||
(* Method for a boxed char *)
|
||||
PROCEDURE (c: Character) INIT*(x: CHAR);
|
||||
BEGIN
|
||||
c.c := x;
|
||||
END INIT;
|
||||
|
||||
PROCEDURE NewCharacter*(c: CHAR): Character;
|
||||
VAR
|
||||
x: Character;
|
||||
BEGIN
|
||||
NEW(x);x.INIT(c);RETURN x
|
||||
END NewCharacter;
|
||||
|
||||
PROCEDURE (c: Character) ToString*(): STRING;
|
||||
BEGIN
|
||||
RETURN Object.NewLatin1Char(c.c);
|
||||
END ToString;
|
||||
|
||||
PROCEDURE (c: Character) Load*(r: Storable.Reader) RAISES IO.Error;
|
||||
BEGIN
|
||||
r.ReadChar(c.c);
|
||||
END Load;
|
||||
|
||||
PROCEDURE (c: Character) Store*(w: Storable.Writer) RAISES IO.Error;
|
||||
BEGIN
|
||||
w.WriteChar(c.c);
|
||||
END Store;
|
||||
|
||||
PROCEDURE (c: Character) Cmp*(o: Object.Object): LONGINT;
|
||||
BEGIN
|
||||
IF c.c < o(Character).c THEN RETURN -1
|
||||
ELSIF c.c = o(Character).c THEN RETURN 0
|
||||
ELSE RETURN 1
|
||||
END
|
||||
END Cmp;
|
||||
(* end of methods for a boxed char *)
|
||||
|
||||
PROCEDURE CheckBalance(str: STRING): BOOLEAN;
|
||||
VAR
|
||||
s: LinkedList.LinkedList(Character);
|
||||
chars: Object.CharsLatin1;
|
||||
n, x: Boxed.Object;
|
||||
i,len: LONGINT;
|
||||
BEGIN
|
||||
i := 0;
|
||||
chars := str(Object.String8).CharsLatin1();
|
||||
len := str.length;
|
||||
s := NEW(LinkedList.LinkedList(Character));
|
||||
WHILE (i < len) & (chars[i] # 0X) DO
|
||||
IF s.IsEmpty() THEN
|
||||
s.Append(NewCharacter(chars[i])) (* Push character *)
|
||||
ELSE
|
||||
n := s.GetLast(); (* top character *)
|
||||
WITH
|
||||
n: Character DO
|
||||
IF (chars[i] = ']') & (n.c = '[') THEN
|
||||
x := s.RemoveLast(); (* Pop character *)
|
||||
x := NIL
|
||||
ELSE
|
||||
s.Append(NewCharacter(chars[i]))
|
||||
END
|
||||
ELSE RETURN FALSE
|
||||
END (* WITH *)
|
||||
END;
|
||||
INC(i)
|
||||
END;
|
||||
RETURN s.IsEmpty()
|
||||
END CheckBalance;
|
||||
|
||||
PROCEDURE Do;
|
||||
VAR
|
||||
str: STRING;
|
||||
BEGIN
|
||||
str := "[]";Out.String(str + ":> "); Out.Bool(CheckBalance(str));Out.Ln;
|
||||
str := "[][]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
|
||||
str := "[[][]]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
|
||||
str := "][";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
|
||||
str := "][][";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
|
||||
str := "[]][[]";Out.String(str + ":> ");Out.Bool(CheckBalance(str));Out.Ln;
|
||||
END Do;
|
||||
|
||||
BEGIN
|
||||
Do
|
||||
END BalancedBrackets.
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
sub balanced($_ is copy) {
|
||||
() while s:g/'[]'//;
|
||||
Nil while s:g/'[]'//;
|
||||
$_ eq '';
|
||||
}
|
||||
|
||||
|
|
|
|||
18
Task/Balanced-brackets/PowerShell/balanced-brackets-1.psh
Normal file
18
Task/Balanced-brackets/PowerShell/balanced-brackets-1.psh
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
function Get-BalanceStatus ( $String )
|
||||
{
|
||||
$Open = 0
|
||||
ForEach ( $Character in [char[]]$String )
|
||||
{
|
||||
switch ( $Character )
|
||||
{
|
||||
"[" { $Open++ }
|
||||
"]" { $Open-- }
|
||||
default { $Open = -1 }
|
||||
}
|
||||
# If Open drops below zero (close before open or non-allowed character)
|
||||
# Exit loop
|
||||
If ( $Open -lt 0 ) { Break }
|
||||
}
|
||||
$Status = ( "NOT OK", "OK" )[( $Open -eq 0 )]
|
||||
return $Status
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
# Test
|
||||
$Strings = @( "" )
|
||||
$Strings += 1..5 | ForEach { ( [char[]]("[]" * $_) | Get-Random -Count ( $_ * 2 ) ) -join "" }
|
||||
|
||||
ForEach ( $String in $Strings )
|
||||
{
|
||||
$String.PadRight( 12, " " ) + (Get-BalanceStatus $String)
|
||||
}
|
||||
57
Task/Balanced-brackets/PowerShell/balanced-brackets-3.psh
Normal file
57
Task/Balanced-brackets/PowerShell/balanced-brackets-3.psh
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
function Test-BalancedBracket
|
||||
{
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Tests a string for balanced brackets.
|
||||
.DESCRIPTION
|
||||
Tests a string for balanced brackets. ("<>", "[]", "{}" or "()")
|
||||
.EXAMPLE
|
||||
Test-BalancedBracket -Bracket Brace -String '{abc(def[0]).xyz}'
|
||||
Test a string for balanced braces.
|
||||
.EXAMPLE
|
||||
Test-BalancedBracket -Bracket Curly -String '{abc(def[0]).xyz}'
|
||||
Test a string for balanced curly braces.
|
||||
.EXAMPLE
|
||||
Test-BalancedBracket -Bracket Curly -String ([System.IO.File]::ReadAllText('.\Foo.ps1'))
|
||||
Test a file for balanced curly braces.
|
||||
.LINK
|
||||
http://go.microsoft.com/fwlink/?LinkId=133231
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
[OutputType([bool])]
|
||||
Param
|
||||
(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[ValidateSet("Angle", "Brace", "Curly", "Paren")]
|
||||
[string]
|
||||
$Bracket,
|
||||
|
||||
[Parameter(Mandatory=$true)]
|
||||
[AllowEmptyString()]
|
||||
[string]
|
||||
$String
|
||||
)
|
||||
|
||||
$notFound = -1
|
||||
|
||||
$brackets = @{
|
||||
Angle = @{Left="<"; Right=">"; Regex="^[^<>]*(?>(?>(?'pair'\<)[^<>]*)+(?>(?'-pair'\>)[^<>]*)+)+(?(pair)(?!))$"}
|
||||
Brace = @{Left="["; Right="]"; Regex="^[^\[\]]*(?>(?>(?'pair'\[)[^\[\]]*)+(?>(?'-pair'\])[^\[\]]*)+)+(?(pair)(?!))$"}
|
||||
Curly = @{Left="{"; Right="}"; Regex="^[^{}]*(?>(?>(?'pair'\{)[^{}]*)+(?>(?'-pair'\})[^{}]*)+)+(?(pair)(?!))$"}
|
||||
Paren = @{Left="("; Right=")"; Regex="^[^()]*(?>(?>(?'pair'\()[^()]*)+(?>(?'-pair'\))[^()]*)+)+(?(pair)(?!))$"}
|
||||
}
|
||||
|
||||
if ($String.IndexOf($brackets.$Bracket.Left) -eq $notFound -and
|
||||
$String.IndexOf($brackets.$Bracket.Right) -eq $notFound -or $String -eq [String]::Empty)
|
||||
{
|
||||
return $true
|
||||
}
|
||||
|
||||
$String -match $brackets.$Bracket.Regex
|
||||
}
|
||||
|
||||
|
||||
'', '[]', '][', '[][]', '][][', '[[][]]', '[]][[]' | ForEach-Object {
|
||||
if ($_ -eq "") { $s = "(Empty)" } else { $s = $_ }
|
||||
"{0}: {1}" -f $s.PadRight(8), "$(if (Test-BalancedBracket Brace $s) {'Is balanced.'} else {'Is not balanced.'})"
|
||||
}
|
||||
|
|
@ -1,38 +1,39 @@
|
|||
/*REXX program checks for balanced (square) brackets [ ] */
|
||||
@.=0; yesNo.0=left('',40) 'unbalanced' /*forty +1 leading blanks.*/
|
||||
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
|
||||
|
||||
do j=1 for 40
|
||||
q=translate(rand(random(1, 8)), '[]', 01)
|
||||
call checkBal q; if result==-1 then iterate /*skip if duplicated.*/
|
||||
say yesNo.result q /*display the result.*/
|
||||
end /*j*/ /* [↑] generate 40 random "Q" strings.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
?: ?=random(0,1); return ? || \?
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
rand: ??=copies(?()?(), arg(1)); _=random(2, length(??))
|
||||
return left(??, _-1)substr(??, _)
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
checkBal: procedure expose @.; parse arg y /*get the "bracket" expression. */
|
||||
if @.y then return -1 /*already done this expression ? */
|
||||
@.y=1 /*indicate expression processed. */
|
||||
!=0; do j=1 for length(y); _=substr(y,j,1) /*get a char.*/
|
||||
if _=='[' then !=!+1 /*bump nest #*/
|
||||
/*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*/
|
||||
@.=0; yesNo.0= right('not OK', 50) /*for bad expressions, indent 50 spaces*/
|
||||
yesNo.1= 'OK' /* [↓] the 14 "fixed" ][ expressions*/
|
||||
q= ; call checkBal q; say yesNo.result '«null»'
|
||||
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
|
||||
#=0 /*# additional random expressions*/
|
||||
do j=1 until #==26 /*gen 26 unique bracket strings. */
|
||||
q=translate( rand( random(1,10) ), '][', 10) /*generate random bracket string.*/
|
||||
call checkBal q; if result==-1 then iterate /*skip if duplicated expression. */
|
||||
say yesNo.result q /*display the result to console. */
|
||||
#=#+1 /*bump the expression counter. */
|
||||
end /*j*/ /* [↑] generate 26 random "Q" strings.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
?: ?=random(0,1); return ? || \? /*REXX BIF*/
|
||||
rand: $=copies(?()?(),arg(1)); _=random(2,length($)); return left($,_-1)substr($,_)
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
checkBal: procedure expose @.; parse arg y /*obtain the "bracket" expression. */
|
||||
if @.y then return -1 /*Done this expression before? Skip it*/
|
||||
@.y=1 /*indicate expression was processed. */
|
||||
!=0; do j=1 for length(y); _=substr(y,j,1) /*get a character.*/
|
||||
if _=='[' then !=!+1 /*bump the nest #.*/
|
||||
else do; !=!-1; if !<0 then return 0; end
|
||||
end /*j*/
|
||||
return !==0 /* [↑] "!" is the nested counter.*/
|
||||
return !==0 /* [↑] "!" is the nested ][ counter.*/
|
||||
|
|
|
|||
|
|
@ -1,23 +1,21 @@
|
|||
/*REXX program checks for numerous generated balanced (square) brackets [ ] */
|
||||
/*REXX program checks for around 125,000 generated balanced brackets expressions [ ] */
|
||||
bals=0
|
||||
#=0; do j=1 until length(q)>20 /*generate lots of bracket permutations*/
|
||||
q=translate(strip(x2b(d2x(j)),'L',0),"][",01) /*convert ──► []*/
|
||||
if countStr(']',q)\==countstr('[',q) then iterate /*is compliant? */
|
||||
call checkBal q
|
||||
end /*j*/ /*have all 20─character possibilities? */
|
||||
say
|
||||
say # " expressions were checked, " bals ' were balanced, ' ,
|
||||
#-bals " were unbalanced."
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
checkBal: procedure expose # bals; parse arg y; #=#+1 /*bump count.*/
|
||||
!=0
|
||||
do j=1 for length(y)
|
||||
if substr(y,j,1)=='[' then !=!+1
|
||||
else do; !=!-1; if !<0 then leave; end
|
||||
end /*j*/
|
||||
bals=bals + (!==0)
|
||||
return !==0
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
#=0; do j=1 until L>20 /*generate lots of bracket permutations*/
|
||||
q=translate( strip( x2b( d2x(j) ), 'L', 0), "][", 01) /*convert ──► ][*/
|
||||
L=length(q)
|
||||
if countStr(']', q) \== countstr('[', q) then iterate /*not compliant?*/
|
||||
#=#+1 /*bump legal Q's*/
|
||||
!=0; do k=1 for L; parse var q ? 2 q
|
||||
if ?=='[' then !=!+1
|
||||
else do; !=!-1; if !<0 then iterate j; end
|
||||
end /*k*/
|
||||
|
||||
if !==0 then bals=bals+1
|
||||
end /*j*/ /*done all 20─character possibilities? */
|
||||
|
||||
say # " expressions were checked, " bals ' were balanced, ' ,
|
||||
#-bals " were unbalanced."
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
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
|
||||
|
|
|
|||
18
Task/Balanced-brackets/Scala/balanced-brackets-4.scala
Normal file
18
Task/Balanced-brackets/Scala/balanced-brackets-4.scala
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
@scala.annotation.tailrec
|
||||
final def isBalanced(
|
||||
str: List[Char],
|
||||
// accumulator|indicator|flag
|
||||
balance: Int = 0,
|
||||
options_Map: Map[Char, Int] = Map(('[' -> 1), (']' -> -1))
|
||||
): Boolean = if (balance < 0) {
|
||||
// base case
|
||||
false
|
||||
} else {
|
||||
if (str.isEmpty){
|
||||
// base case
|
||||
balance == 0
|
||||
} else {
|
||||
// recursive step
|
||||
isBalanced(str.tail, balance + options_Map(str.head))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
fun isBalanced s = checkBrackets 0 (String.explode s)
|
||||
and checkBrackets 0 [] = true
|
||||
| checkBrackets _ [] = false
|
||||
| checkBrackets ~1 _ = false
|
||||
| checkBrackets counter (#"["::rest) = checkBrackets (counter + 1) rest
|
||||
| checkBrackets counter (#"]"::rest) = checkBrackets (counter - 1) rest
|
||||
| checkBrackets counter (_::rest) = checkBrackets counter rest
|
||||
11
Task/Balanced-brackets/Standard-ML/balanced-brackets-2.ml
Normal file
11
Task/Balanced-brackets/Standard-ML/balanced-brackets-2.ml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
val () =
|
||||
List.app print
|
||||
(List.map
|
||||
(* Turn `true' and `false' to `OK' and `NOT OK' respectively *)
|
||||
(fn s => if isBalanced s
|
||||
then s ^ "\t\tOK\n"
|
||||
else s ^ "\t\tNOT OK\n"
|
||||
)
|
||||
(* A set of strings to test *)
|
||||
["", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"]
|
||||
)
|
||||
|
|
@ -1,15 +1,5 @@
|
|||
@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end)
|
||||
@(do (defvar r (make-random-state nil))
|
||||
(defun shuffle (list)
|
||||
(for* ((vec (vector-list list))
|
||||
(len (length vec))
|
||||
(i 0))
|
||||
((< i len) (list-vector vec))
|
||||
((inc i))
|
||||
(let ((j (random r len))
|
||||
(temp [vec i]))
|
||||
(set [vec i] [vec j])
|
||||
(set [vec j] temp))))
|
||||
|
||||
(defun generate-1 (count)
|
||||
(let ((bkt (repeat "[]" count)))
|
||||
|
|
|
|||
|
|
@ -0,0 +1,17 @@
|
|||
10 FOR n=1 TO 7
|
||||
20 READ s$
|
||||
25 PRINT "The sequence ";s$;" is ";
|
||||
30 GO SUB 1000
|
||||
40 NEXT n
|
||||
50 STOP
|
||||
1000 LET s=0
|
||||
1010 FOR k=1 TO LEN s$
|
||||
1020 LET c$=s$(k)
|
||||
1030 IF c$="[" THEN LET s=s+1
|
||||
1040 IF c$="]" THEN LET s=s-1
|
||||
1050 IF s<0 THEN PRINT "Bad!": RETURN
|
||||
1060 NEXT k
|
||||
1070 IF s=0 THEN PRINT "Good!": RETURN
|
||||
1090 PRINT "Bad!"
|
||||
1100 RETURN
|
||||
2000 DATA "[]","][","][][","[][]","[][][]","[]][[]","[[[[[]]]]][][][]][]["
|
||||
Loading…
Add table
Add a link
Reference in a new issue