Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -0,0 +1,95 @@
CLASS lcl_balanced_brackets DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
class_constructor,
are_brackets_balanced
IMPORTING
seq TYPE string
RETURNING
VALUE(r_are_brackets_balanced) TYPE abap_bool,
get_random_brackets_seq
IMPORTING
n TYPE i
RETURNING
VALUE(r_bracket_seq) TYPE string.
PRIVATE SECTION.
CLASS-DATA: random_int TYPE REF TO cl_abap_random_int.
CLASS-METHODS:
_split_string
IMPORTING
i_text TYPE string
RETURNING
VALUE(r_chars) TYPE stringtab,
_rand_bool
RETURNING
VALUE(r_bool) TYPE i.
ENDCLASS.
CLASS lcl_balanced_brackets IMPLEMENTATION.
METHOD class_constructor.
random_int = cl_abap_random_int=>create( seed = CONV #( sy-uzeit )
min = 0
max = 1 ).
ENDMETHOD.
METHOD are_brackets_balanced.
DATA: open_bracket_count TYPE i.
DATA(chars) = _split_string( seq ).
r_are_brackets_balanced = abap_false.
LOOP AT chars ASSIGNING FIELD-SYMBOL(<c>).
IF <c> = ']' AND open_bracket_count = 0.
RETURN.
ENDIF.
IF <c> = ']'.
open_bracket_count = open_bracket_count - 1.
ENDIF.
IF <c> = '['.
open_bracket_count = open_bracket_count + 1.
ENDIF.
ENDLOOP.
IF open_bracket_count > 0.
RETURN.
ENDIF.
r_are_brackets_balanced = abap_true.
ENDMETHOD.
METHOD get_random_brackets_seq.
DATA(itab) = VALUE stringtab( FOR i = 1 THEN i + 1 WHILE i <= n
( COND #( WHEN _rand_bool( ) = 0 THEN '['
ELSE ']' ) ) ).
r_bracket_seq = concat_lines_of( itab ).
ENDMETHOD.
METHOD _rand_bool.
r_bool = random_int->get_next( ).
ENDMETHOD.
METHOD _split_string.
DATA: off TYPE i VALUE 0.
DO strlen( i_text ) TIMES.
INSERT i_text+off(1) INTO TABLE r_chars.
off = off + 1.
ENDDO.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DO 10 TIMES.
DATA(seq) = lcl_balanced_brackets=>get_random_brackets_seq( 10 ).
cl_demo_output=>write( |{ seq } => { COND string( WHEN lcl_balanced_brackets=>are_brackets_balanced( seq ) = abap_true THEN 'OK'
ELSE 'NOT OK' ) }| ).
ENDDO.
cl_demo_output=>display( ).

View file

@ -0,0 +1,63 @@
# 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:
BEGIN
INT result length = length * 2;
[ 1 : result length ]CHAR result;
# initialise the brackets to all open brackets #
FOR char pos TO result length DO result[ char pos ] := "[" OD;
# set half of the brackets to close brackets #
INT close count := 0;
WHILE close count < length
DO
INT random pos = 1 + ENTIER ( next random * result length );
IF result[ random pos ] = "["
THEN
close count +:= 1;
result[ random pos ] := "]"
FI
OD;
result
END # get brackets # ;
# returns TRUE if the brackets string contains a correctly nested sequence #
# of brackets, FALSE otherwise #
PROC check brackets = ( STRING brackets ) BOOL:
BEGIN
INT depth := 0;
FOR char pos FROM LWB brackets TO UPB brackets
WHILE
IF brackets[ char pos ] = "["
THEN
depth +:= 1
ELSE
depth -:= 1
FI;
depth >= 0
DO
SKIP
OD;
# depth will be 0 if we reached the end of the string and it was #
# correct, non-0 otherwise #
depth = 0
END # check brackets # ;
# procedure to test check brackets #
PROC test check brackets = ( STRING brackets ) VOID:
print( ( ( brackets
+ ": "
+ IF check brackets( brackets ) THEN "ok" ELSE "not ok" FI
)
, newline
)
) ;
# test the bracket generation and checking PROCs #
test check brackets( get brackets( 0 ) );
FOR length TO 12
DO
TO 2
DO
test check brackets( get brackets( length ) )
OD
OD

View file

@ -0,0 +1,63 @@
:: Balanced Brackets Task from Rosetta Code Wiki
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
::The Main Thing...
set numofpairs=10
set howmanystrings=10
cls
for /l %%. in (1,1,%howmanystrings%) do (
call :generate
call :checkforbalance
)
echo.&pause&exit /b
::/The Main Thing.
::Generate strings of brackets...
:generate
set i=0&set j=%numofpairs%&set samp=
set /a toss=%random%%%2
set put1=[&set put2=]
if %toss%==1 (set put1=]&set put2=[)
for /l %%x in (1,1,%numofpairs%) do (
set samp=!samp!%put1%
)
:add
if not %i%==%numofpairs% (
set /a rnd=%random%%%%j%+1
set /a oppos=%j%-!rnd!
::A new trick for substitution of delayed variables...
for /f "tokens=1-2" %%A in ("!rnd! !oppos!") do (
set str1=!samp:~-%%A!
set str2=!samp:~0,%%B!
)
set samp=!str2!%put2%!str1!
set /a "j+=1","i+=1"
goto :add
)
goto :EOF
::/Generate strings of brackets.
::Check for Balance...
::Uses Markov Algorithm.
:checkforbalance
set "changes=!samp!"
:check_loop
if "!changes!"=="" goto itsbal
if "!input!"=="!changes!" goto notbal
set input=!changes!
set "changes=!input:[]=!"
goto check_loop
:itsbal
echo.
echo %samp% is Balanced.
goto :EOF
:notbal
echo.
echo %samp% is NOT Balanced.
goto :EOF
::/Check for Balance.

View file

@ -2,40 +2,42 @@
#define system'routines.
#define extensions.
// --- RandomBrackets ---
#symbol randomBrackets =
{
new : aLength
= (0 == aLength)
? [ emptyLiteralValue ]
! [
#var aBrackets :=
Array new &length:(aLength int) set &every: (&index:i) [ #91 ]
+
Array new &length:(aLength int) set &every: (&index:i)[ #93 ].
#symbol randomBrackets = (:aLength)
[
^ (0 == aLength)
? [ emptyLiteralValue ]
! [
#var aBrackets := arrayControl new &length:(aLength int) &each: i[ CharValue new &short:91 ] + arrayControl new &length:(aLength int) &each: i[ CharValue new &short:93 ].
aBrackets randomize:(aLength * 2).
randomControl randomize:(aLength * 2) &array:aBrackets.
^ aBrackets summarize:(String new) literal.
].
}.
^ Summing new:(String new) foreach:aBrackets literal.
].
].
#class(extension)op
{
#method isBalanced
[
#var aCounter := Integer new:0.
#symbol isBalanced = (:aLiteral)
[
#var aCounter := Integer new:0.
self seek &each:aChar [ (aCounter += (aChar => #91 ? [ 1 ] #93 ? [ -1 ])) < 0 ].
control foreach:aLiteral &until: aChar [ aCounter append:(aChar => "[" ? [ 1 ] "]" ? [ -1 ]) < 0 ].
^ (0 == aCounter).
].
// --- Program ---
^ (0 == aCounter).
]
}
#symbol program =
[
control forrange &int:0 &int:9 &do: (&int:aLength)
0 to:9 &doEach: (:aLength)
[
#var anStr := randomBrackets:aLength.
#var balanced := isBalanced:anStr.
#var anStr := randomBrackets new:aLength.
consoleEx writeLine:"""":anStr:"""":(balanced => true ? [ " is balanced" ] false ? [ " is not balanced" ]).
console writeLine:"""":anStr:"""":((anStr isBalanced) => true ? [ " is balanced" ] false ? [ " is not balanced" ]).
].
console readChar.

View file

@ -0,0 +1,30 @@
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}"
end)
end
def generate( 0 ), do: []
def generate( n ) do
for _ <- 1..2*n, do: generate_bracket(:rand.uniform(2))
end
defp generate_bracket( 1 ), do: "["
defp generate_bracket( 2 ), do: "]"
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( [], 0 ), do: true
defp is_balanced_loop( [], _n ), do: false
defp is_balanced_loop( ["[" | t], n ), do: is_balanced_loop( t, n + 1 )
defp is_balanced_loop( ["]" | t], n ), do: is_balanced_loop( t, n - 1 )
defp task_balanced( true ), do: "OK"
defp task_balanced( false ), do: "NOT OK"
end
Balanced_brackets.task

View file

@ -1,4 +1,4 @@
(,&' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10
(, ' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10
OK
][ bad
][[] bad

View file

@ -7,6 +7,6 @@ function balanced(str)
i == 0 ? true : false
end
brackets(n) = CharString(shuffle([("[]"^n)...]))
brackets(n) = join(shuffle([("[]"^n)...]))
print(map(x -> (x, balanced(x)), [brackets(i) for i = 0:8]))
map(x -> (x, balanced(x)), [brackets(i) for i = 0:8])

View file

@ -0,0 +1,33 @@
#!/usr/bin/php
<?php
# brackets generator
function bgenerate ($n) {
if ($n==0) return '';
$s = str_repeat('[', $n) . str_repeat(']', $n);
return str_shuffle($s);
}
function printbool($b) {return ($b) ? 'OK' : 'NOT OK';}
function isbalanced($s) {
$bal = 0;
for ($i=0; $i < strlen($s); $i++) {
$ch = substr($s, $i, 1);
if ($ch == '[') {
$bal++;
} else {
$bal--;
}
if ($bal < 0) return false;
}
return ($bal == 0);
}
# test parameters are N (see spec)
$tests = array(0, 2,2,2, 3,3,3, 4,4,4,4);
foreach ($tests as $v) {
$s = bgenerate($v);
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL);
}

View file

@ -13,5 +13,5 @@ sub balanced($s) {
}
my $n = prompt "Number of brackets";
my $s = (<[ ]> xx $n).pick(*).join;
my $s = (<[ ]> xx $n).flat.pick(*).join;
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"

View file

@ -5,4 +5,4 @@ sub balanced($_ is copy) {
my $n = prompt "Number of bracket pairs: ";
my $s = <[ ]>.roll($n*2).join;
say "$s is", ' not' xx not balanced($s)), " well-balanced";
say "$s is", ' not' x not balanced($s), " well-balanced";

View file

@ -1,5 +1,5 @@
grammar BalBrack { token TOP { '[' <TOP>* ']' } }
my $n = prompt "Number of bracket pairs: ";
my $s = ('[' xx $n, ']' xx $n).pick(*).join;
my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join;
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";

View file

@ -1,40 +1,38 @@
/*REXX program to check for balanced brackets [] */
@.=0
yesno.0 = left('',40) 'unbalanced'
yesno.1 = 'balanced'
/*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
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
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 #*/
else do; !=!-1; if !<0 then return 0; end
end /*j*/
return !==0 /* [↑] "!" is the nested counter.*/

View file

@ -1,58 +1,23 @@
/*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?*/
/*REXX program checks for numerous generated balanced (square) brackets [ ] */
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
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
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
/*────────────────────────────────────────────────────────────────────────────*/
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,40 @@
extern crate rand;
trait Balanced {
/// Returns true if the brackets are balanced
fn is_balanced(&self) -> bool;
}
impl<'a> Balanced for str {
fn is_balanced(&self) -> bool {
let mut count = 0;
for bracket in self.chars() {
let change = match bracket {
'[' => 1,
']' => -1,
_ => panic!("Strings should only contain brackets")
};
count += change;
if count < 0 { return false; }
}
count == 0
}
}
/// Generates random brackets
fn generate_brackets(num: usize) -> String {
use rand::random;
(0..num).map(|_| if random() { '[' } else { ']' }).collect()
}
fn main() {
for i in (0..10) {
let brackets = generate_brackets(i);
println!("{} {}", brackets, brackets.is_balanced())
}
}

View file

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