Data update

This commit is contained in:
Ingy döt Net 2026-02-01 16:33:20 -08:00
parent 5150844a7d
commit 4bb20c9b71
7735 changed files with 38060 additions and 199180 deletions

View file

@ -11,11 +11,11 @@ BEGIN {
function isbb(x) {
s = 0
for (k=1; k<=length(x); k++) {
c = substr(x,k,1)
if (c=="[") {s++}
else { if (c=="]") s-- }
c = substr(x,k,1)
if (c=="[") {s++}
else { if (c=="]") s-- }
if (s<0) {return 0}
}
}
return (s==0)
}

View file

@ -1,57 +0,0 @@
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

@ -2,11 +2,10 @@ isBalanced: function [s][
cnt: 0
loop split s [ch][
if? ch="]" [
switch ch="]" [
cnt: cnt-1
if cnt<0 -> return false
]
else [
][
if ch="[" -> cnt: cnt+1
]
]
@ -19,6 +18,6 @@ loop 1..10 'i [
prints str
if? isBalanced str -> print " OK"
else -> print " Not OK"
switch isBalanced str -> print " OK"
-> print " Not OK"
]

View file

@ -1,32 +1,32 @@
; Generate 10 strings with equal left and right brackets
Loop, 5
{
B = %A_Index%
loop 2
{
String =
Loop % B
String .= "[`n"
Loop % B
String .= "]`n"
Sort, String, Random
StringReplace, String, String,`n,,All
Example .= String " - " IsBalanced(String) "`n"
}
B = %A_Index%
loop 2
{
String =
Loop % B
String .= "[`n"
Loop % B
String .= "]`n"
Sort, String, Random
StringReplace, String, String,`n,,All
Example .= String " - " IsBalanced(String) "`n"
}
}
MsgBox % Example
MsgBox % Example
return
IsBalanced(Str)
{
Loop, PARSE, Str
{
If A_LoopField = [
i++
Else if A_LoopField = ]
i--
If i < 0
return "NOT OK"
}
Return "OK"
Loop, PARSE, Str
{
If A_LoopField = [
i++
Else if A_LoopField = ]
i--
If i < 0
return "NOT OK"
}
Return "OK"
}

View file

@ -1,23 +1,23 @@
Loop, 5
{
B = %A_Index%
loop 2
{
String =
Loop % B
String .= "[`n"
Loop % B
String .= "]`n"
Sort, String, Random
StringReplace, String, String,`n,,All
Example .= String " - " IsBalanced(String) "`n"
}
B = %A_Index%
loop 2
{
String =
Loop % B
String .= "[`n"
Loop % B
String .= "]`n"
Sort, String, Random
StringReplace, String, String,`n,,All
Example .= String " - " IsBalanced(String) "`n"
}
}
MsgBox % Example
MsgBox % Example
return
IsBalanced(Str){
While (Instr(Str,"[]"))
StringReplace, Str, Str,[],,All
Return Str ? "False" : "True"
While (Instr(Str,"[]"))
StringReplace, Str, Str,[],,All
Return Str ? "False" : "True"
}

View file

@ -1,28 +0,0 @@
#include <Array.au3>
Local $Array[1]
_ArrayAdd($Array, "[]")
_ArrayAdd($Array, "[][]")
_ArrayAdd($Array, "[[][]]")
_ArrayAdd($Array, "][")
_ArrayAdd($Array, "][][")
_ArrayAdd($Array, "[]][[]")
For $i = 0 To UBound($Array) -1
Balanced_Brackets($Array[$i])
If @error Then
ConsoleWrite($Array[$i] &" = NOT OK"&@CRLF)
Else
ConsoleWrite($Array[$i] &" = OK"&@CRLF)
EndIf
Next
Func Balanced_Brackets($String)
Local $cnt = 0
$Split = Stringsplit($String, "")
For $i = 1 To $Split[0]
If $split[$i] = "[" Then $cnt += 1
If $split[$i] = "]" Then $cnt -= 1
If $cnt < 0 Then Return SetError(1,0,0)
Next
Return 1
EndFunc

View file

@ -1,12 +0,0 @@
(defun BalancedBrackets (str / cntOpen curr)
(setq cntOpen 0)
(setq str (vl-string->list str))
(while (and (>= cntOpen 0) str)
(setq curr (car str) str (cdr str))
(cond
((= 91 curr) (setq cntOpen (1+ cntOpen)))
((= 93 curr) (setq cntOpen (1- cntOpen)))
)
)
(and (null str) (zerop cntOpen))
)

View file

@ -1,23 +1,23 @@
// simple solution
string input = Console.ReadLine();
if (input.Length % 2 != 0)
{
Console.WriteLine("Not Okay");
return;
}
for (int i = 0; i < input.Length; i++)
{
if (i < input.Length - 1)
{
if (input[i] == '[' && input[i + 1] == ']')
{
input = input.Remove(i, 2);
i = -1;
}
}
}
if (input.Length == 0)
Console.WriteLine("Okay");
else
Console.WriteLine("Not Okay");
if (input.Length % 2 != 0)
{
Console.WriteLine("Not Okay");
return;
}
for (int i = 0; i < input.Length; i++)
{
if (i < input.Length - 1)
{
if (input[i] == '[' && input[i + 1] == ']')
{
input = input.Remove(i, 2);
i = -1;
}
}
}
if (input.Length == 0)
Console.WriteLine("Okay");
else
Console.WriteLine("Not Okay");

View file

@ -5,25 +5,25 @@
int isBal(const char*s,int l){
signed c=0;
while(l--)
if(s[l]==']') ++c;
else if(s[l]=='[') if(--c<0) break;
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;
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);
memset(s,'[',n);
memset(s+n,']',n);
shuffle(s,n*2);
}
s[n*2]=0;
}

View file

@ -1,98 +0,0 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. test-balanced-brackets.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 True-Val CONSTANT 0.
01 False-Val CONSTANT 1.
LOCAL-STORAGE SECTION.
01 current-time PIC 9(10).
01 bracket-type PIC 9.
88 add-open-bracket VALUE 1.
01 bracket-string-area.
03 bracket-string PIC X(10) OCCURS 10 TIMES.
01 i PIC 999.
01 j PIC 999.
PROCEDURE DIVISION.
*> Seed RANDOM().
MOVE FUNCTION CURRENT-DATE (7:10) TO current-time
MOVE FUNCTION RANDOM(current-time) TO current-time
*> Generate random strings of brackets.
PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i
PERFORM VARYING j FROM 1 BY 1 UNTIL i < j
COMPUTE bracket-type =
FUNCTION REM(FUNCTION RANDOM * 1000, 2)
IF add-open-bracket
MOVE "[" TO bracket-string (i) (j:1)
ELSE
MOVE "]" TO bracket-string (i) (j:1)
END-IF
END-PERFORM
END-PERFORM
*> Display if the strings are balanced or not.
PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i
CALL "check-if-balanced" USING bracket-string (i)
IF RETURN-CODE = True-Val
DISPLAY FUNCTION TRIM(bracket-string (i))
" is balanced."
ELSE
DISPLAY FUNCTION TRIM(bracket-string (i))
" is not balanced."
END-IF
END-PERFORM
GOBACK
.
END PROGRAM test-balanced-brackets.
IDENTIFICATION DIVISION.
PROGRAM-ID. check-if-balanced.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 True-Val CONSTANT 0.
01 False-Val CONSTANT 1.
LOCAL-STORAGE SECTION.
01 nesting-level PIC S999.
01 i PIC 999.
LINKAGE SECTION.
01 bracket-string PIC X(100).
PROCEDURE DIVISION USING bracket-string.
PERFORM VARYING i FROM 1 BY 1
UNTIL (100 < i)
OR (bracket-string (i:1) = SPACE)
OR (nesting-level < 0)
IF bracket-string (i:1) = "["
ADD 1 TO nesting-level
ELSE
SUBTRACT 1 FROM nesting-level
IF nesting-level < 0
MOVE False-Val TO RETURN-CODE
GOBACK
END-IF
END-IF
END-PERFORM
IF nesting-level = 0
MOVE True-Val TO RETURN-CODE
ELSE
MOVE False-Val TO RETURN-CODE
END-IF
GOBACK
.
END PROGRAM check-if-balanced.

View file

@ -5,10 +5,10 @@
(defn balanced? [s]
(loop [[first & coll] (seq s)
stack '()]
stack '()]
(if first
(if (= first \[)
(recur coll (conj stack \[))
(when (= (peek stack) \[)
(recur coll (pop stack))))
(recur coll (conj stack \[))
(when (= (peek stack) \[)
(recur coll (pop stack))))
(zero? (count stack)))))

View file

@ -2,59 +2,59 @@ MODULE Brackets;
IMPORT StdLog, Args, Stacks (* See Task Stacks *);
TYPE
Character = POINTER TO RECORD (Stacks.Object)
c: CHAR
END;
Character = POINTER TO RECORD (Stacks.Object)
c: CHAR
END;
PROCEDURE NewCharacter(c: CHAR): Character;
VAR
n: Character;
n: Character;
BEGIN
NEW(n);n.c:= c;RETURN n
NEW(n);n.c:= c;RETURN n
END NewCharacter;
PROCEDURE (c: Character) Show*;
BEGIN
StdLog.String("Character(");StdLog.Char(c.c);StdLog.String(");");StdLog.Ln
StdLog.String("Character(");StdLog.Char(c.c);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE CheckBalance(str: ARRAY OF CHAR): BOOLEAN;
VAR
s: Stacks.Stack;
n,x: ANYPTR;
i: INTEGER;
c : CHAR;
s: Stacks.Stack;
n,x: ANYPTR;
i: INTEGER;
c : CHAR;
BEGIN
i := 0; s := Stacks.NewStack();
WHILE (i < LEN(str$)) & (~Args.IsBlank(str[i])) & (str[i] # 0X) DO
IF s.Empty() THEN
s.Push(NewCharacter(str[i]));
ELSE
n := s.top.data;
WITH
n : Character DO
IF (str[i] = ']')& (n.c = '[') THEN
x := s.Pop();
ELSE
s.Push(NewCharacter(str[i]))
END;
ELSE RETURN FALSE;
END;
END;
INC(i)
END;
RETURN s.Empty();
i := 0; s := Stacks.NewStack();
WHILE (i < LEN(str$)) & (~Args.IsBlank(str[i])) & (str[i] # 0X) DO
IF s.Empty() THEN
s.Push(NewCharacter(str[i]));
ELSE
n := s.top.data;
WITH
n : Character DO
IF (str[i] = ']')& (n.c = '[') THEN
x := s.Pop();
ELSE
s.Push(NewCharacter(str[i]))
END;
ELSE RETURN FALSE;
END;
END;
INC(i)
END;
RETURN s.Empty();
END CheckBalance;
PROCEDURE Do*;
VAR
p : Args.Params;
i: INTEGER;
p : Args.Params;
i: INTEGER;
BEGIN
Args.Get(p); (* Get Params *)
FOR i := 0 TO p.argc - 1 DO
StdLog.String(p.args[i] + ":>");StdLog.Bool(CheckBalance(p.args[i]));StdLog.Ln
END
Args.Get(p); (* Get Params *)
FOR i := 0 TO p.argc - 1 DO
StdLog.String(p.args[i] + ":>");StdLog.Bool(CheckBalance(p.args[i]));StdLog.Ln
END
END Do;
END Brackets.

View file

@ -6,9 +6,7 @@ func balanced code$ .
elif h$ = "]"
br -= 1
.
if br < 0
return 0
.
if br < 0 : return 0
.
return if br = 0
.

View file

@ -1,17 +1,17 @@
(define (balance str)
(for/fold (closed 0) ((par str))
#:break (< closed 0 ) => closed
(+ closed
(cond
((string=? par "[") 1)
((string=? par "]") -1)
(else 0)))))
(for/fold (closed 0) ((par str))
#:break (< closed 0 ) => closed
(+ closed
(cond
((string=? par "[") 1)
((string=? par "]") -1)
(else 0)))))
(define (task N)
(define str (list->string (append (make-list N "[") (make-list N "]"))))
(for ((i 10))
(set! str (list->string (shuffle (string->list str))))
(writeln (if (zero? (balance str)) '👍 '❌ ) str)))
(for ((i 10))
(set! str (list->string (shuffle (string->list str))))
(writeln (if (zero? (balance str)) '👍 '❌ ) str)))
(task 4)
@ -25,4 +25,3 @@
❌ "]][[][[]"
❌ "[[]]][[]"
❌ "[[][]]]["

View file

@ -33,7 +33,7 @@ extension op
}
}
public program()
public Program()
{
for(int len := 0; len < 9; len += 1)
{

View file

@ -2,17 +2,17 @@
-export( [generate/1, is_balanced/1, task/0] ).
generate( N ) ->
[generate_bracket(random:uniform()) || _X <- lists:seq(1, 2*N)].
[generate_bracket(random:uniform()) || _X <- lists:seq(1, 2*N)].
is_balanced( String ) -> is_balanced_loop( String, 0 ).
task() ->
lists:foreach( fun (N) ->
String = generate( N ),
Result = is_balanced( String ),
io:fwrite( "~s is ~s~n", [String, task_balanced(Result)] )
end,
lists:seq(0, 5) ).
lists:foreach( fun (N) ->
String = generate( N ),
Result = is_balanced( String ),
io:fwrite( "~s is ~s~n", [String, task_balanced(Result)] )
end,
lists:seq(0, 5) ).

View file

@ -1,45 +0,0 @@
function check_brackets(sequence s)
integer level
level = 0
for i = 1 to length(s) do
if s[i] = '[' then
level += 1
elsif s[i] = ']' then
level -= 1
if level < 0 then
return 0
end if
end if
end for
return level = 0
end function
function generate_brackets(integer n)
integer opened,closed,r
sequence s
opened = n
closed = n
s = ""
for i = 1 to n*2 do
r = rand(opened+closed)
if r<=opened then
s &= '['
opened -= 1
else
s &= ']'
closed -= 1
end if
end for
return s
end function
sequence s
for i = 1 to 10 do
s = generate_brackets(3)
puts(1,s)
if check_brackets(s) then
puts(1," OK\n")
else
puts(1," NOT OK\n")
end if
end for

View file

@ -1,40 +1,40 @@
extends MainLoop
func generate_brackets(n: int) -> String:
var brackets: Array[String] = []
var brackets: Array[String] = []
# Add opening and closing brackets
brackets.resize(2*n)
for i in range(0, 2*n, 2):
brackets[i] = "["
brackets[i+1] = "]"
# Add opening and closing brackets
brackets.resize(2*n)
for i in range(0, 2*n, 2):
brackets[i] = "["
brackets[i+1] = "]"
brackets.shuffle()
return "".join(brackets)
brackets.shuffle()
return "".join(brackets)
func is_balanced(str: String) -> bool:
var unclosed_brackets := 0
for c in str:
match c:
"[":
unclosed_brackets += 1
"]":
if unclosed_brackets == 0:
return false
unclosed_brackets -= 1
_:
return false
return unclosed_brackets == 0
var unclosed_brackets := 0
for c in str:
match c:
"[":
unclosed_brackets += 1
"]":
if unclosed_brackets == 0:
return false
unclosed_brackets -= 1
_:
return false
return unclosed_brackets == 0
func _process(_delta: float) -> bool:
randomize()
randomize()
for i in range(6):
var bracket_string := generate_brackets(i)
for i in range(6):
var bracket_string := generate_brackets(i)
if is_balanced(bracket_string):
print("%sOK" % bracket_string.rpad(13))
else:
print("%sNOT OK" % bracket_string.rpad(11))
if is_balanced(bracket_string):
print("%sOK" % bracket_string.rpad(13))
else:
print("%sNOT OK" % bracket_string.rpad(11))
return true # Exit
return true # Exit

View file

@ -2,63 +2,63 @@ import java.util.ArrayDeque;
import java.util.Deque;
public class BalancedBrackets {
public static boolean areSquareBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "[", "]", false);
}
public static boolean areBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "{([", "})]", false);
}
public static boolean areStringAndBracketsBalanced(String expr) {
return isBalanced(expr, "'\"", "\\\\", "{([", "})]", true);
}
public static boolean isBalanced(String expr, String lit, String esc, String obr, String cbr, boolean other) {
boolean[] inLit = new boolean[lit.length()];
Deque<Character> stack = new ArrayDeque<Character>();
for (int i=0; i<expr.length(); i+=1) {
char c = get(expr, i);
int x;
if ((x = indexOf(inLit, true)) != -1) {
if (c == get(lit, x) && get(expr, i-1) != get(esc, x)) inLit[x] = false;
}
else if ((x = indexOf(lit, c)) != -1)
inLit[x] = true;
else if ((x = indexOf(obr, c)) != -1)
stack.push(get(cbr, x));
else if (indexOf(cbr, c) != -1) {
if (stack.isEmpty() || stack.pop() != c) return false;
}
else if (!other)
return false;
}
return stack.isEmpty();
}
static int indexOf(boolean[] a, boolean b) {
for (int i=0; i<a.length; i+=1) if (a[i] == b) return i;
return -1;
}
static int indexOf(String s, char c) {
return s.indexOf(c);
}
static char get(String s, int i) {
return s.charAt(i);
}
public static void main(String[] args) {
System.out.println("With areSquareBracketsBalanced:");
for (String s: new String[] {
"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]", "[", "]"
}
) {
System.out.printf("%s: %s\n", s, areSquareBracketsBalanced(s));
}
System.out.println("\nBut also with areStringAndBracketsBalanced:");
for (String s: new String[] {
"x[]", "[x]", "[]x", "([{}])", "([{}]()", "([{ '([{\\'([{' \"([{\\\"([{\" }])",
}
) {
System.out.printf("%s: %s\n", s, areStringAndBracketsBalanced(s));
}
}
public static boolean areSquareBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "[", "]", false);
}
public static boolean areBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "{([", "})]", false);
}
public static boolean areStringAndBracketsBalanced(String expr) {
return isBalanced(expr, "'\"", "\\\\", "{([", "})]", true);
}
public static boolean isBalanced(String expr, String lit, String esc, String obr, String cbr, boolean other) {
boolean[] inLit = new boolean[lit.length()];
Deque<Character> stack = new ArrayDeque<Character>();
for (int i=0; i<expr.length(); i+=1) {
char c = get(expr, i);
int x;
if ((x = indexOf(inLit, true)) != -1) {
if (c == get(lit, x) && get(expr, i-1) != get(esc, x)) inLit[x] = false;
}
else if ((x = indexOf(lit, c)) != -1)
inLit[x] = true;
else if ((x = indexOf(obr, c)) != -1)
stack.push(get(cbr, x));
else if (indexOf(cbr, c) != -1) {
if (stack.isEmpty() || stack.pop() != c) return false;
}
else if (!other)
return false;
}
return stack.isEmpty();
}
static int indexOf(boolean[] a, boolean b) {
for (int i=0; i<a.length; i+=1) if (a[i] == b) return i;
return -1;
}
static int indexOf(String s, char c) {
return s.indexOf(c);
}
static char get(String s, int i) {
return s.charAt(i);
}
public static void main(String[] args) {
System.out.println("With areSquareBracketsBalanced:");
for (String s: new String[] {
"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]", "[", "]"
}
) {
System.out.printf("%s: %s\n", s, areSquareBracketsBalanced(s));
}
System.out.println("\nBut also with areStringAndBracketsBalanced:");
for (String s: new String[] {
"x[]", "[x]", "[]x", "([{}])", "([{}]()", "([{ '([{\\'([{' \"([{\\\"([{\" }])",
}
) {
System.out.printf("%s: %s\n", s, areStringAndBracketsBalanced(s));
}
}
}

View file

@ -1,19 +1,19 @@
grammar balancedBrackets ;
options {
language = Java;
language = Java;
}
bb : {System.out.print("input is: ");} (balancedBrackets {System.out.print($balancedBrackets.text);})* NEWLINE {System.out.println();}
;
bb : {System.out.print("input is: ");} (balancedBrackets {System.out.print($balancedBrackets.text);})* NEWLINE {System.out.println();}
;
balancedBrackets
: OpenBracket balancedBrackets* CloseBracket
;
: OpenBracket balancedBrackets* CloseBracket
;
OpenBracket
: '['
;
: '['
;
CloseBracket
: ']'
;
NEWLINE : '\r'? '\n'
;
: ']'
;
NEWLINE : '\r'? '\n'
;

View file

@ -1,26 +1,26 @@
module Balanced_brackets{
// Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
function randomBrackets(max as long) {
if max<1 then max=1
def putbracket()=mid$("[[[[]]",random(1,6),1)
dim a(random(1, max)) as string<<putbracket()
=a()#str$("")
}
// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
function check(s as string) {
long i, level
for i=1 to len(s)
if mid$(s,i,1)="[" then level++ else level--
if level<0 then exit for
next
=level=0
}
string k
boolean m
do
k=randomBrackets(10)
m=check(k)
print k;@(12);": ";if$(m->"OK", "NOT OK")
until m
// Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
function randomBrackets(max as long) {
if max<1 then max=1
def putbracket()=mid$("[[[[]]",random(1,6),1)
dim a(random(1, max)) as string<<putbracket()
=a()#str$("")
}
// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
function check(s as string) {
long i, level
for i=1 to len(s)
if mid$(s,i,1)="[" then level++ else level--
if level<0 then exit for
next
=level=0
}
string k
boolean m
do
k=randomBrackets(10)
m=check(k)
print k;@(12);": ";if$(m->"OK", "NOT OK")
until m
}
Balanced_brackets

View file

@ -25,16 +25,16 @@ balanced(S) :- imbalance(S,0).
brackets(N,S,!RS) :-
(
N < 1 -> S is []
N < 1 -> S is []
; random(0,2,R,!RS),
( R is 0 -> S is ['['|T], brackets(N-1,T,!RS)
; S is [']'|T], brackets(N-1,T,!RS))).
( R is 0 -> S is ['['|T], brackets(N-1,T,!RS)
; S is [']'|T], brackets(N-1,T,!RS))).
main(!IO) :-
random.init(0,RS),
brackets(4,S,RS,_),
print(S,!IO),
(
balanced(S) -> print(" is balanced\n",!IO)
balanced(S) -> print(" is balanced\n",!IO)
; print(" is unbalanced\n", !IO)
).

View file

@ -1,9 +1,9 @@
isBalanced = function(str)
level = 0
for c in str
if c == "[" then level = level + 1
if c == "]" then level = level - 1
if level < 0 then return false
end for
return level == 0
level = 0
for c in str
if c == "[" then level = level + 1
if c == "]" then level = level - 1
if level < 0 then return false
end for
return level == 0
end function

View file

@ -9,7 +9,7 @@ examples = [
"[[[]"]
for str in examples
balanced = isBalanced(str)
if balanced then outcome = "is OK" else outcome = "NOT OK"
print """" + str + """ " + outcome
balanced = isBalanced(str)
if balanced then outcome = "is OK" else outcome = "NOT OK"
print """" + str + """ " + outcome
end for

View file

@ -1,33 +1,33 @@
import Nanoquery.Util
def gen(N)
txt = {"[", "]"} * N
txt = new(Random).shuffle(txt)
return "".join("", txt)
txt = {"[", "]"} * N
txt = new(Random).shuffle(txt)
return "".join("", txt)
end
def balanced(txt)
braced = 0
for ch in txt
if ch = "["
braced += 1
else if ch = "]"
braced -= 1
end
if braced < 0
return false
end
end
return braced = 0
braced = 0
for ch in txt
if ch = "["
braced += 1
else if ch = "]"
braced -= 1
end
if braced < 0
return false
end
end
return braced = 0
end
// unlike Python, the range function is inclusive in Nanoquery
for N in range(1, 10)
txt = gen(N)
if balanced(txt)
println format("%-22s is balanced", txt)
else
println format("%-22s is not balanced", txt)
end
txt = gen(N)
if balanced(txt)
println format("%-22s is balanced", txt)
else
println format("%-22s is not balanced", txt)
end
end

View file

@ -1,11 +1,11 @@
def gen_brackets [n: int] { 1..$in | each {["[" "]"]} | flatten | shuffle | str join }
def check_brackets [] {
split chars | reduce --fold 0 {|x, d|
if ($d < 0) {-1} else {
$d + (if ($x == "[") {1} else {-1})
}
} | $in > -1
split chars | reduce --fold 0 {|x, d|
if ($d < 0) {-1} else {
$d + (if ($x == "[") {1} else {-1})
}
} | $in > -1
}

View file

@ -1,18 +0,0 @@
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
}

View file

@ -1,8 +0,0 @@
# Test
$Strings = @( "" )
$Strings += 1..5 | ForEach { ( [char[]]("[]" * $_) | Get-Random -Count ( $_ * 2 ) ) -join "" }
ForEach ( $String in $Strings )
{
$String.PadRight( 12, " " ) + (Get-BalanceStatus $String)
}

View file

@ -1,57 +0,0 @@
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.'})"
}

View file

@ -1,52 +1,52 @@
rosetta_brackets :-
test_brackets([]),
test_brackets(['[',']']),
test_brackets(['[',']','[',']']),
test_brackets(['[','[',']','[',']',']']),
test_brackets([']','[']),
test_brackets([']','[',']','[']),
test_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).
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')
).
( 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 -->
['[',']'],
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).
{N1 is N - 1,
R is random(2)},
bracket(R),
gen_bracket(N1).
bracket(0) --> ['['].
bracket(1) --> [']'].

View file

@ -5,18 +5,18 @@ balanced?: func [str][parse str rule]
; Tests
tests: [
good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"]
bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"]
good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"]
bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"]
]
foreach str tests/good [
if not balanced? str [print [mold str "failed!"]]
if not balanced? str [print [mold str "failed!"]]
]
foreach str tests/bad [
if balanced? str [print [mold str "failed!"]]
if balanced? str [print [mold str "failed!"]]
]
repeat i 10 [
str: random copy/part "[][][][][][][][][][]" i * 2
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]]
str: random copy/part "[][][][][][][][][][]" i * 2
print [mold str "is" either balanced? str ["balanced"]["unbalanced"]]
]

View file

@ -1,12 +1,12 @@
mata
function random_brackets(n) {
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],""))
return(invtokens(("[","]")[runiformint(1,2*n,1,2)],""))
}
function is_balanced(s) {
n = strlen(s)
if (n==0) return(1)
a = runningsum(92:-ascii(s))
return(all(a:>=0) & a[n]==0)
n = strlen(s)
if (n==0) return(1)
a = runningsum(92:-ascii(s))
return(all(a:>=0) & a[n]==0)
}
end

View file

@ -3,9 +3,9 @@ proc generate {n} {
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
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 ""]
}
@ -13,11 +13,11 @@ proc generate {n} {
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}}
}
# Everything unmatched is ignored, which is what we want
switch -exact -- $c {
"\[" {incr n}
"\]" {if {[incr n -1] < 0} {return false}}
}
}
expr {!$n}
}

View file

@ -1,8 +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]"
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
}

View file

@ -1,36 +0,0 @@
For n = 1 To 10
sequence = Generate_Sequence(n)
WScript.Echo sequence & " is " & Check_Balance(sequence) & "."
Next
Function Generate_Sequence(n)
For i = 1 To n
j = Round(Rnd())
If j = 0 Then
Generate_Sequence = Generate_Sequence & "["
Else
Generate_Sequence = Generate_Sequence & "]"
End If
Next
End Function
Function Check_Balance(s)
Set Stack = CreateObject("System.Collections.Stack")
For i = 1 To Len(s)
char = Mid(s,i,1)
If i = 1 Or char = "[" Then
Stack.Push(char)
ElseIf Stack.Count <> 0 Then
If char = "]" And Stack.Peek = "[" Then
Stack.Pop
End If
Else
Stack.Push(char)
End If
Next
If Stack.Count > 0 Then
Check_Balance = "Not Balanced"
Else
Check_Balance = "Balanced"
End If
End Function

View file

@ -1,40 +0,0 @@
option explicit
function do_brackets(bal)
dim s,i,cnt,r
if bal then s="[":cnt=1 else s="":cnt=0
for i=1 to 20
if (rnd>0.7) then r=not r
if not r then
s=s+"[" :cnt=cnt+1
else
if not bal or (bal and cnt>0) then s=s+"]":cnt=cnt-1
end if
next
if bal and cnt<>0 then s=s&string(cnt,"]")
if not bal and cnt=0 then s=s&"]"
do_brackets=s
end function
function isbalanced(s)
dim s1,i,cnt: cnt=0
for i=1 to len(s)
s1=mid(s,i,1)
if s1="[" then cnt=cnt+1
if s1="]" then cnt=cnt-1
if cnt<0 then isbalanced=false:exit function
next
isbalanced=(cnt=0)
end function
function iif(a,b,c): if a then iif=b else iif=c end if : end function
randomize timer
dim i,s,bal,bb
for i=1 to 10
bal=(rnd>.5)
s=do_brackets(bal)
bb=isbalanced(s)
wscript.echo iif (bal,"","un")& "balanced string " &vbtab _
& s & vbtab & " Checks as " & iif(bb,"","un")&"balanced"
next

View file

@ -1,17 +1,17 @@
const Chars:[string] = ["[","]"];
func GenerateString(Amount:number=4):string{
set Result:string = "";
<|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)];
send Result;
set Result:string = "";
<|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)];
send Result;
}
func IsBalanced(String:string):boolean{
set Pairs:number = 0;
<|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>Pairs--;
send (Opens==Closes)&(Pairs==0);
set Pairs:number = 0;
<|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>Pairs--;
send (Opens==Closes)&(Pairs==0);
}
repeat 10 {
set s = GenerateString(math.random(2,4)*2);
log(`{s}: {IsBalanced(s)}`);
set s = GenerateString(math.random(2,4)*2);
log(`{s}: {IsBalanced(s)}`);
}

View file

@ -4,34 +4,34 @@
// definition of anything new is prefixed by \, like \MakeNew_[]s and \len
// MakeNew_[]s is Ok ident in Ya: _ starts sign part of ident, which must be ended by _ or alphanum
`Char[^] \MakeNew_[]s(`Int+ \len) // `Char[^] and `Char[=] are arrays that owns their items, like it's usally in other langs;
// yet in assignment of `Char[^] to `Char[=] the allocated memory is moved from old to new owner, and old string becomes empty
// there are tabs at starts of many lines; these tabs specify what in C++ is {} blocks, just like in Python
len & 1 ==0 ! // it's a call to postfix function '!' which is an assert: len must be even
`Char[=] \r(len) // allocate new string of length len
// most statements are analogous to C++ but written starting by capital letter: For If Switch Ret
For `Char[] \eye = r; eye // // `Char[] is a simplest array of chars, which does not hold a memory used by array items; inc part of For loop is missed: it's Ok, and condition and init could also be missed
*eye++ = '['; *eye++ = '[' // fill r by "[][][]...". The only place with ; as statement delemiter: required because the statement is not started at new line.
// below is a shuffle of "[][][]..." array
For `Char[] \eye = r; ++eye // var eye is already defined, but being the same `Char[] it's Ok by using already exisiting var. ++eye is used: it allows use of eye[-1] inside
`Int+ \at = Random(eye/Length) // `Int+ is C++'s unsigned int. eye/Length: / is used for access to field, like in file path
eye[-1],eye[at] = eye[at],eye[-1] // swap using tuples; eye[-1] accesses char that is out of current array, yet it's allowed
Ret r // Ret is C's return
// yet in assignment of `Char[^] to `Char[=] the allocated memory is moved from old to new owner, and old string becomes empty
// there are tabs at starts of many lines; these tabs specify what in C++ is {} blocks, just like in Python
len & 1 ==0 ! // it's a call to postfix function '!' which is an assert: len must be even
`Char[=] \r(len) // allocate new string of length len
// most statements are analogous to C++ but written starting by capital letter: For If Switch Ret
For `Char[] \eye = r; eye // // `Char[] is a simplest array of chars, which does not hold a memory used by array items; inc part of For loop is missed: it's Ok, and condition and init could also be missed
*eye++ = '['; *eye++ = '[' // fill r by "[][][]...". The only place with ; as statement delemiter: required because the statement is not started at new line.
// below is a shuffle of "[][][]..." array
For `Char[] \eye = r; ++eye // var eye is already defined, but being the same `Char[] it's Ok by using already exisiting var. ++eye is used: it allows use of eye[-1] inside
`Int+ \at = Random(eye/Length) // `Int+ is C++'s unsigned int. eye/Length: / is used for access to field, like in file path
eye[-1],eye[at] = eye[at],eye[-1] // swap using tuples; eye[-1] accesses char that is out of current array, yet it's allowed
Ret r // Ret is C's return
`Bool \AreBalanced(`Char[] \brackets)
`Int+ \extra = 0
For ;brackets ;++brackets
Switch *brackets
'[' // it's a C++'s 'case': both 'case' and ':' are skipped being of no value; but the code for a case should be in block, which is here specifyed by tabs at next line start
++extra
']'
If !!extra // '!!' is `Bool not, like all other `Bool ops: && || ^^
Ret No // No and False are C's false; Yes and True are C's true
--extra
// There is no default case, which is written as ':' - so if no case is Ok then it will fail just like if being written as on the next line
// : { 0! } // C's default: assert(0);
Ret extra == 0
`Int+ \extra = 0
For ;brackets ;++brackets
Switch *brackets
'[' // it's a C++'s 'case': both 'case' and ':' are skipped being of no value; but the code for a case should be in block, which is here specifyed by tabs at next line start
++extra
']'
If !!extra // '!!' is `Bool not, like all other `Bool ops: && || ^^
Ret No // No and False are C's false; Yes and True are C's true
--extra
// There is no default case, which is written as ':' - so if no case is Ok then it will fail just like if being written as on the next line
// : { 0! } // C's default: assert(0);
Ret extra == 0
// function ala 'main' is not used: all global code from all modules are executed; so below is what typically is in ala 'main'
For `Int \n=10; n; --n
// below note that new var 'brackets' is created inside args of func call
//@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop
@Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad")
// note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written
// below note that new var 'brackets' is created inside args of func call
//@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop
@Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad")
// note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written

View file

@ -1,6 +1,6 @@
sub check_brackets(s$)
local level, i
for i = 1 to len(s$)
switch mid$(s$, i, 1)
case "[": level = level + 1 : break