September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,11 +1,11 @@
integer
unbalanced(text s)
unbalanced(data s)
{
integer b, i;
b = 0;
i = 0;
while (i < length(s)) {
while (i < b_length(s)) {
if (s[i] == '[') {
b += 1;
} else {
@ -24,22 +24,15 @@ unbalanced(text s)
text
generate(integer d)
{
integer i;
text s;
list l;
data b;
i = d;
while (i) {
s = insert(s, 0, '[');
i -= 1;
}
l_pn_integer(l, 0, d, '[');
l_pn_integer(l, 0, d, ']');
l_rand(l);
l_ucall(l, b_append, 1, b);
i = d;
while (i) {
s = insert(s, drand(length(s)), ']');
i -= 1;
}
return s;
return b;
}
integer
@ -52,12 +45,7 @@ main(void)
text s;
s = generate(i);
o_text(s);
o_text(" is ");
if (unbalanced(s)) {
o_text("un");
}
o_text("balanced\n");
o_plan(s, " is ", unbalanced(s) ? "un" : "", "balanced\n");
i += 1;
}

View file

@ -1,4 +1,4 @@
-- CHECK NESTING OF SQUARE BRACKET SEQUENCES
-- CHECK NESTING OF SQUARE BRACKET SEQUENCES ---------------------------------
-- Zero-based index of the first problem (-1 if none found):
@ -28,32 +28,30 @@ on imbalance(strBrackets)
result's errorIndex(characters of strBrackets, 0, 0)
end imbalance
-- TEST
-- TEST ----------------------------------------------------------------------
-- Random bracket sequences for testing
-- brackets :: Int -> String
on brackets(n)
on randomBrackets(n)
-- bracket :: () -> String
script bracket
on lambda(_)
on |λ|(_)
cond((random number) < 0.5, "[", "]")
end lambda
end |λ|
end script
intercalate("", map(bracket, range(1, n)))
end brackets
intercalate("", map(bracket, enumFromTo(1, n)))
end randomBrackets
on run
set nPairs to 6
-- report :: Int -> String
script report
property strPad : concatReplicate(nPairs * 2 + 4, space)
property strPad : concat(replicate(nPairs * 2 + 4, space))
on lambda(n)
on |λ|(n)
set w to n * 2
set s to brackets(w)
set s to randomBrackets(w)
set i to imbalance(s)
set blnOK to (i = -1)
@ -62,19 +60,20 @@ on run
set strLine to "'" & s & "'" & ¬
(items (w + 2) thru -1 of strPad) & strStatus
set strPointer to cond(blnOK, "", linefeed & concatReplicate(i + 1, space) & "^")
set strPointer to cond(blnOK, ¬
"", linefeed & concat(replicate(i + 1, space)) & "^")
intercalate("", {strLine, strPointer})
end lambda
end |λ|
end script
linefeed & ¬
intercalate(linefeed, ¬
map(report, range(0, nPairs))) & linefeed
map(report, enumFromTo(1, nPairs))) & linefeed
end run
-- GENERIC LIBRARY FUNCTIONS
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
@ -82,7 +81,7 @@ on map(f, xs)
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)
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
@ -94,7 +93,7 @@ on foldl(f, startValue, xs)
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)
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
@ -108,10 +107,21 @@ on intercalate(strText, lstText)
return strJoined
end intercalate
-- concatReplicate :: Int -> String -> String
on concatReplicate(n, s)
concat(replicate(n, s))
end concatReplicate
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
script append
on |λ|(a, b)
a & b
end |λ|
end script
if length of xs > 0 and class of (item 1 of xs) is string then
set empty to ""
else
set empty to {}
end if
foldl(append, empty, xs)
end concat
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
@ -131,21 +141,6 @@ on replicate(n, a)
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)
@ -155,15 +150,15 @@ on cond(bln, f, g)
set e to g
end if
if class of e is handler then
mReturn(e)'s lambda()
mReturn(e)'s |λ|()
else
e
end if
end cond
-- range :: Int -> Int -> [Int]
on range(m, n)
if n < m then
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
@ -173,7 +168,7 @@ on range(m, n)
set end of lst to i
end repeat
return lst
end range
end enumFromTo
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
@ -182,7 +177,7 @@ on mReturn(f)
f
else
script
property lambda : f
property |λ| : f
end script
end if
end mReturn

View file

@ -1,44 +1,45 @@
#define system.
#define system'routines.
#define extensions.
import system'routines.
import extensions.
#symbol randomBrackets =
randomBrackets =
{
new : aLength
= (0 == aLength)
? [ emptyLiteralValue ]
! [
#var aBrackets :=
Array new &length:(aLength int) set &every: (&index:i) [ #91 ]
[
if (0 == aLength)
[ ^emptyLiteralValue ];
[
var aBrackets :=
Array new length:(aLength int); populate(:i)($91)
+
Array new &length:(aLength int) set &every: (&index:i)[ #93 ].
Array new length:(aLength int); populate(:i)($93).
aBrackets randomize:(aLength * 2).
aBrackets := aBrackets randomize:(aLength * 2).
^ aBrackets summarize:(String new) literal.
].
^ aBrackets summarize:(String new); literal
]
]
}.
#class(extension)op
extension op
{
#method isBalanced
isBalanced
[
#var aCounter := Integer new:0.
var aCounter := Integer new:0.
self seek &each:aChar [ (aCounter += (aChar => #91 ? [ 1 ] #93 ? [ -1 ])) < 0 ].
self seekEach(:aChar)(aCounter append((aChar==$91)iif (1,-1)) < 0).
^ (0 == aCounter).
^ (0 == aCounter)
]
}
#symbol program =
program =
[
0 to:9 &doEach: (:aLength)
0 to:9 do(:aLength)
[
#var anStr := randomBrackets new:aLength.
var anStr := randomBrackets new:aLength.
console writeLine:"""":anStr:"""":((anStr isBalanced) => true ? [ " is balanced" ] false ? [ " is not balanced" ]).
console printLine("""",anStr,"""",anStr isBalanced; iif(" is balanced"," is not balanced"))
].
console readChar.
console readChar
].

View file

@ -0,0 +1,20 @@
USING: io formatting locals kernel math sequences unicode.case ;
IN: balanced-brackets
: map-braces ( -- qout )
[
{
{ "[" [ drop 1 ] }
{ "]" [ drop -1 ] }
[ drop 0 ]
} case
]
;
: balanced? ( str -- ? )
map-braces map sum 0 =
;
"[1+2*[3+4*[5+6]-3]*4-[3*[3+3]]]" balanced?
-- Data stack:
t

View file

@ -0,0 +1,73 @@
'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work
siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line
siNumberOfLines As Short = 20 'Amount of lines to test
'----
Public Sub Main()
Dim sBrks As String[] = GenerateBrackets() 'Get random array to check
Dim sTemp, sHold, sWork As String 'Working variables
Dim siCount As Short 'Counter
For Each sTemp In sBrks 'For each line in the sBrk array (e.g. '[][][][[[[]][]]]')
sWork = sTemp 'Make sWork = sTemp
Repeat 'Repeat
sHold = sWork 'Make sHold = sWork
sWork = Replace(sWork, "[]", "") 'Remove all brackets that match '[]'
Until sHold = sWork 'If sHold = sWork then there are no more '[]' matches
If sWork = "" Then 'So if all the brackets 'Nested' correctly sWork will be empty
Print " OK "; 'Print 'OK'
Else 'Else they did not all match
Print "NOT OK "; 'So print 'NOT OK'
Endif
For siCount = 1 To Len(sTemp) 'Loop through the line of brackets
Print Mid(sTemp, siCount, 1) & " "; 'Print each bracket + a space to make it easier to read
Next
Print 'Print a new line
Next
End
'----
Public Sub GenerateBrackets() As String[] 'Generates an array of random quantities of '[' and ']'
Dim siQty As New Short[] 'To store the random number (of brackets) to put in a line
Dim sBrk As New String[] 'To store the lines of brackets
Dim siNum, siEnd, siLoop As Short 'Various counters
Dim sTemp As String 'Temp string
Repeat 'Repeat
siNum = Rand(0, siNumberOfBrackets) 'Pick a number between 0 and the total number of brackets requested
If Even(siNum) Then siQty.Add(siNum) 'If the number is even then add the number to siQty
Until siQty.Count = siNumberOfLines 'Keep going until we have the number of lines requested
For Each siNum In siQty 'For each number in siQty..(e.g. 6)
Do
siEnd = Rand(0, 1) 'Generate a 0 or a 1
If siEnd = 0 Then sTemp &= "[" 'If '0' then add a '[' bracket
If siEnd = 1 Then sTemp &= "]" 'If '1' then add a ']' bracket
If siNum = 0 Then 'If siNum = 0 then..
sBrk.Add("") 'Add '0' to the array
sTemp = "" 'Clear sTemp
Break 'Exit the Do Loop
Endif
If Len(sTemp) = siNum Then 'If the length of sTemp = the required amount then..
If sTemp Not Begins "]" And sTemp Not Ends "[" Then 'Check to see that sTemp does not start with "]" and does not end with a "["
sBrk.Add(sTemp) 'Add it to the array
sTemp = "" 'Clear sTemp
Break 'Exit the Do Loop
Else 'Else
sTemp = "" 'Clear sTemp
End If 'Try again!
Endif
Loop
Next
Return sBrk 'Return the sBrk array
End

View file

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

View file

@ -0,0 +1,32 @@
import java.util.Random
fun isBalanced(s: String): Boolean {
if (s.isEmpty()) return true
var countLeft = 0 // number of left brackets so far unmatched
for (c in s) {
if (c == '[') countLeft++
else if (countLeft > 0) countLeft--
else return false
}
return countLeft == 0
}
fun main(args: Array<String>) {
println("Checking examples in task description:")
val brackets = arrayOf("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
for (b in brackets) {
print(if (b != "") b else "(empty)")
println("\t " + if (isBalanced(b)) "OK" else "NOT OK")
}
println()
println("Checking 7 random strings of brackets of length 8:")
val r = Random()
(1..7).forEach {
var s = ""
for (j in 1..8) {
s += if (r.nextInt(2) == 0) '[' else ']'
}
println("$s " + if (isBalanced(s)) "OK" else "NOT OK")
}
}

View file

@ -1,16 +1,10 @@
import random
from random import random, randomize, shuffle
from strutils import repeat
randomize()
proc shuffle(s: var string) =
for i in countdown(s.high, 0):
swap(s[i], s[random(s.len)])
proc gen(n: int): string =
result = newString(2 * n)
for i in 0 .. <n:
result[i] = '['
for i in n .. <(2*n):
result[i] = ']'
result = "[]".repeat(n)
shuffle(result)
proc balanced(txt: string): bool =

View file

@ -0,0 +1,47 @@
tests = .array~of("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]")
-- add some randomly generated tests
loop i = 1 to 8
tests~append(generateBrackets(i))
end
loop test over tests
say test":" checkbrackets(test)
end
::routine checkBrackets
use arg input
-- counter of bracket groups. Must be 0 at end to be valid
groups = 0
-- loop over all of the characters
loop c over input~makearray("")
if c == '[' then groups += 1
else if c == ']' then groups -= 1
else return .false -- non-bracket char found
-- check for a close occurring before an open
if groups < 0 then return .false
end
-- should be zero at the end
return groups == 0
-- generate a string with n pairs of brackets
::routine generateBrackets
use arg n
answer = .mutablebuffer~new(,2*n)
openBracketsNeeded = n
unclosedBrackets = 0
loop while answer~length < 2 * n
if random(0, 1) & openBracketsNeeded > 0 | unclosedBrackets == 0 then do
answer~append('[')
openBracketsNeeded -= 1
unclosedBrackets += 1
end
else do
answer~append(']')
unclosedBrackets -= 1
end
end
return answer~string

View file

@ -0,0 +1,6 @@
function varargout=isbb(s)
st=strsplit(s);
t=cumsum((st=='[')-(st==']'));
balanced=and(t>=0) & t(length(t))==0;
varargout=list(balanced)
endfunction

View file

@ -0,0 +1,14 @@
for j=[5 16 22]
s=[];
for i=1:j
p=rand();
if p>0.5 then
s=s+"[";
else
s=s+"]";
end
end
disp(s);
x=isbb(s);
disp(x);
end

View file

@ -1,14 +1,14 @@
func balanced (str) {
var depth = 0;
var depth = 0
str.each { |c|
if(c=='['){ ++depth }
elsif(c==']'){ --depth < 0 && return false }
};
}
return !depth;
return !depth
}
[']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'].each { |str|
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str);
};
for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] {
printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str)
}

View file

@ -0,0 +1 @@
fcn bb(bs){ while(a:=bs.span("[","]")) {bs=bs[a[1],*]} (Void!=a) }