June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -5,8 +5,11 @@
;Examples:
(empty) OK
[] OK ][ NOT OK
[][] OK ][][ NOT OK
[[][]] OK []][[] NOT OK
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
<br><br>

View file

@ -0,0 +1,58 @@
.data
balanced_message:
.ascii "OK\n"
unbalanced_message:
.ascii "NOT OK\n"
.text
.equ balanced_msg_len, 3
.equ unbalanced_msg_len, 7
BalancedBrackets:
mov r1, #0
mov r2, #0
mov r3, #0
process_bracket:
ldrb r2, [r0, r1]
cmp r2, #0
beq evaluate_balance
cmp r2, #'['
addeq r3, r3, #1
cmp r2, #']'
subeq r3, r3, #1
cmp r3, #0
blt unbalanced
add r1, r1, #1
b process_bracket
evaluate_balance:
cmp r3, #0
beq balanced
unbalanced:
ldr r1, =unbalanced_message
mov r2, #unbalanced_msg_len
b display_result
balanced:
ldr r1, =balanced_message
mov r2, #balanced_msg_len
display_result:
mov r7, #4
mov r0, #1
svc #0
mov pc, lr

View file

@ -0,0 +1,21 @@
10 PRINT CHR$(147): REM CLEAR SCREEN
20 FOR N=1 TO 7
30 READ S$
40 IF S$="" THEN PRINT"(EMPTY)";: GOTO 60
50 PRINT S$;
60 PRINT TAB(20);
70 GOSUB 1000
80 NEXT N
90 END
100 REM ********************************
1000 S = 0
1010 FOR K=1 TO LEN(S$)
1020 C$ = MID$(S$,K,1)
1030 IF C$="[" THEN S = S+1
1040 IF C$="]" THEN S = S-1
1050 IF S<0 THEN PRINT "NOT OK": RETURN
1060 NEXT K
1070 IF S=0 THEN PRINT "OK": RETURN
1090 PRINT "NOT OK"
1100 RETURN
2000 DATA , [], ][, [][], ][][, [[][]], []][[]

View file

@ -1,21 +1,22 @@
import system'routines.
import extensions.
import extensions'text.
randomBrackets =
{
new : aLength
[
if (0 == aLength)
[ ^emptyLiteralValue ];
[ ^emptyLiteral ];
[
var aBrackets :=
Array new length:(aLength int); populate(:i)($91)
Array new(aLength); populate(:i)($91)
+
Array new length:(aLength int); populate(:i)($93).
Array new(aLength); populate(:i)($93).
aBrackets := aBrackets randomize:(aLength * 2).
^ aBrackets summarize:(String new); literal
^ aBrackets summarize:(StringWriter new); toLiteral
]
]
}.
@ -32,7 +33,7 @@ extension op
]
}
program =
public program =
[
0 to:9 do(:aLength)
[

View file

@ -1,12 +1,14 @@
function balanced(str)
i = 0
for c in str
if c == '[' i +=1 elseif c == ']' i -=1 end
if i < 0 return false end
end
i == 0 ? true : false
function balancedbrackets(str::AbstractString)
i = 0
for c in str
if c == '[' i += 1 elseif c == ']' i -=1 end
if i < 0 return false end
end
return i == 0
end
brackets(n) = join(shuffle([("[]"^n)...]))
brackets(n::Integer) = join(shuffle(collect(Char, "[]" ^ n)))
map(x -> (x, balanced(x)), [brackets(i) for i = 0:8])
for (test, pass) in map(x -> (x, balancedbrackets(x)), collect(brackets(i) for i = 0:8))
@printf("%22s%10s\n", test, pass ? "pass" : "fail")
end

View file

@ -1 +1 @@
balanced(str) = foldl((x,y)->x<0? -1: x+y, 0, [(x=='[')-(x==']') for x=str])==0
balancedbrackets(str::AbstractString) = foldl((x, y) -> x < 0 ? -1 : x + y, 0, collect((x == '[') - (x == ']') for x in str)) == 0

View file

@ -1,6 +1,6 @@
sub balanced($s) {
.none < 0 and .[*-1] == 0
given [\+] '\\' «leg« $s.comb;
given ([\+] '\\' «leg« $s.comb).cache;
}
my $n = prompt "Number of bracket pairs: ";

View file

@ -0,0 +1,24 @@
>>> from itertools import accumulate
>>> from random import shuffle
>>> def gen(n):
... txt = list('[]' * n)
... shuffle(txt)
... return ''.join(txt)
...
>>> def balanced(txt):
... brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt)
... return all(x>=0 for x in accumulate(brackets))
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'][' is not balanced
'[]][' is not balanced
']][[[]' is not balanced
'][[][][]' is not balanced
'[[[][][]]]' is balanced
'][[[][][]][]' is not balanced
'][]][][[]][[][' is not balanced
'][[]]][][[]][[[]' is not balanced
'][[][[]]]][[[]][][' is not balanced

View file

@ -0,0 +1,25 @@
>>> import numpy as np
>>> from random import shuffle
>>> def gen(n):
... txt = list('[]' * n)
... shuffle(txt)
... return ''.join(txt)
...
>>> m = np.array([{'[': 1, ']': -1}.get(chr(c), 0) for c in range(128)])
>>> def balanced(txt):
... a = np.array(txt, 'c').view(np.uint8)
... return np.all(m[a].cumsum() >= 0)
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'][' is not balanced
'[[]]' is balanced
'[]][][' is not balanced
']][]][[[' is not balanced
'[[]][[][]]' is balanced
'[][[]][[]]][' is not balanced
'[][[[]][[]]][]' is balanced
'[[][][[]]][[[]]]' is balanced
'][]][][[]][]][][[[' is not balanced

View file

@ -1,4 +1,4 @@
rand.parens <- function(n) paste(permute(c(rep('[',n),rep(']',n))),collapse="")
rand.parens <- function(n) paste(sample(c("[","]"),2*n,replace=T),collapse="")
as.data.frame(within(list(), {
parens <- replicate(10, rand.parens(sample.int(10,size=1)))

View file

@ -0,0 +1,22 @@
; Functional code
balanced-brackets: [#"[" any balanced-brackets #"]"]
rule: [any balanced-brackets end]
balanced?: func [str][parse str rule]
; Tests
tests: [
good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"]
bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"]
]
foreach str tests/good [
if not balanced? str [print [mold str "failed!"]]
]
foreach str tests/bad [
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"]]
]

View file

@ -0,0 +1,12 @@
mata
function random_brackets(n) {
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)
}
end

View file

@ -0,0 +1,44 @@
Module Module1
Private rand As New Random
Sub Main()
For numInputs As Integer = 1 To 10 '10 is the number of bracket sequences to test.
Dim input As String = GenerateBrackets(rand.Next(0, 5)) '5 represents the number of pairs of brackets (n)
Console.WriteLine(String.Format("{0} : {1}", input.PadLeft(10, CChar(" ")), If(IsBalanced(input) = True, "OK", "NOT OK")))
Next
Console.ReadLine()
End Sub
Private Function GenerateBrackets(n As Integer) As String
Dim randomString As String = ""
Dim numOpen, numClosed As Integer
Do Until numOpen = n And numClosed = n
If rand.Next(0, 501) Mod 2 = 0 AndAlso numOpen < n Then
randomString = String.Format("{0}{1}", randomString, "[")
numOpen += 1
ElseIf rand.Next(0, 501) Mod 2 <> 0 AndAlso numClosed < n Then
randomString = String.Format("{0}{1}", randomString, "]")
numClosed += 1
End If
Loop
Return randomString
End Function
Private Function IsBalanced(brackets As String) As Boolean
Dim numOpen As Integer = 0
Dim numClosed As Integer = 0
For Each character As Char In brackets
If character = "["c Then numOpen += 1
If character = "]"c Then
numClosed += 1
If numClosed > numOpen Then Return False
End If
Next
Return numOpen = numClosed
End Function
End Module

View file

@ -0,0 +1,66 @@
section .data
MsgBalanced: db "OK", 10
MsgBalancedLen: equ 3
MsgUnbalanced: db "NOT OK", 10
MsgUnbalancedLen: equ 7
MsgBadInput: db "BAD INPUT", 10
MsgBadInputLen: equ 10
Open: equ '['
Closed: equ ']'
section .text
BalancedBrackets:
xor rcx, rcx
mov rsi, rdi
cld
processBracket:
lodsb
cmp al, 0
je determineBalance
cmp al, Open
je processOpenBracket
cmp al, Closed
je processClosedBracket
mov rsi, MsgBadInput
mov rdx, MsgBadInputLen
jmp displayResult
processOpenBracket:
add rcx, 1
jmp processBracket
processClosedBracket:
cmp rcx, 0
je unbalanced
sub rcx, 1
jmp processBracket
determineBalance:
cmp rcx, 0
jne unbalanced
mov rsi, MsgBalanced
mov rdx, MsgBalancedLen
jmp displayResult
unbalanced:
mov rsi, MsgUnbalanced
mov rdx, MsgUnbalancedLen
displayResult:
mov rax, 1
mov rdi, 1
syscall
ret