Add tasks for all the new languages

This commit is contained in:
Tina Müller 2016-12-05 23:44:36 +01:00
parent 9dc3c2bb62
commit bba7bfd280
13208 changed files with 134745 additions and 0 deletions

View file

@ -0,0 +1,27 @@
import com.vasileff.ceylon.random.api {
platformRandom,
Random
}
"""Run the example code for Rosetta Code ["Balanced brackets" task] (http://rosettacode.org/wiki/Balanced_brackets)."""
shared void run() {
value rnd = platformRandom();
for (len in (0..10)) {
value c = generate(rnd, len);
print("``c.padTrailing(20)`` - ``if (balanced(c)) then "OK" else "NOT OK" ``");
}
}
String generate(Random rnd, Integer count)
=> if (count == 0) then ""
else let(length = 2*count,
brackets = zipEntries(rnd.integers(length).take(length),
"[]".repeat(count))
.sort((a,b) => a.key<=>b.key)
.map(Entry.item))
String(brackets);
Boolean balanced(String input)
=> let (value ints = { for (c in input) if (c == '[') then 1 else -1 })
ints.filter((i) => i != 0)
.scan(0)(plus<Integer>)
.every((i) => i >= 0);

View file

@ -0,0 +1,28 @@
(define (balance str)
(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)))
(task 4)
❌ "[]]][[]["
❌ "]][][[[]"
❌ "][[[]]]["
👍 "[][[[]]]"
❌ "]][[][]["
❌ "][][[[]]"
👍 "[][][[]]"
❌ "]][[][[]"
❌ "[[]]][[]"
❌ "[[][]]]["

View file

@ -0,0 +1,45 @@
' FB 1.05.0 Win64
Function isBalanced(s As String) As Boolean
If s = "" Then Return True
Dim countLeft As Integer = 0 '' counts number of left brackets so far unmatched
Dim c As String
For i As Integer = 1 To Len(s)
c = Mid(s, i, 1)
If c = "[" Then
countLeft += 1
ElseIf countLeft > 0 Then
countLeft -= 1
Else
Return False
End If
Next
Return countLeft = 0
End Function
' checking examples in task description
Dim brackets(1 To 7) As String = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"}
For i As Integer = 1 To 7
Print IIf(brackets(i) <> "", brackets(i), "(empty)"); Tab(10); IIf(isBalanced(brackets(i)), "OK", "NOT OK")
Next
' checking 7 random strings of brackets of length 8 say
Randomize
Dim r As Integer '' 0 will signify "[" and 1 will signify "]"
Dim s As String
For i As Integer = 1 To 7
s = Space(8)
For j As Integer = 1 To 8
r = Int(Rnd * 2)
If r = 0 Then
Mid(s, j) = "["
Else
Mid(s, j) = "]"
End If
Next j
Print s; Tab(10); IIf(isBalanced(s), "OK", "NOT OK")
Next i
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,15 @@
(include "string")
(defn bool balanced (std::string s)
(def bal 0)
(foreach c s
(if (== c #\[) (++ bal)
(if (== c #\]) (-- bal)))
(if (< bal 0) (return false)))
(return (== bal 0)))
(main
(decl std::string (at tests) |{"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]"}|)
(pr std::boolalpha)
(foreach x tests
(prn x "\t" (balanced x))))

View file

@ -0,0 +1,22 @@
define randomparens(num::integer,open::string='[',close::string=']') => {
local(out) = array
with i in 1 to #num do {
#out->insert(']', integer_random(1,#out->size || 1))
#out->insert('[', integer_random(1,#out->size || 1))
}
return #out->join
}
define validateparens(input::string,open::string='[',close::string=']') => {
local(i) = 0
#input->foreachcharacter => {
#1 == #open ? #i++
#1 == #close && --#i < 0 ? return false
}
return #i == 0 ? true | false
}
with i in 1 to 10
let input = randomparens(#i)
select #input + ' = ' + validateparens(#input)

View file

@ -0,0 +1,30 @@
import random
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] = ']'
shuffle(result)
proc balanced(txt: string): bool =
var b = 0
for c in txt:
case c
of '[':
inc(b)
of ']':
dec(b)
if b < 0: return false
else: discard
b == 0
for n in 0..9:
let s = gen(n)
echo "'", s, "' is ", (if balanced(s): "balanced" else: "not balanced")

View file

@ -0,0 +1,11 @@
String method: isBalanced
| c |
0 self forEach: c [
c '[' == ifTrue: [ 1+ continue ]
c ']' <> ifTrue: [ continue ]
1- dup 0 < ifTrue: [ drop false return ]
]
0 == ;
: genBrackets(n)
"" #[ "[" "]" 2 rand 2 == ifTrue: [ swap ] rot + swap + ] times(n) ;

View file

@ -0,0 +1,21 @@
function check_brackets(sequence s)
integer level = 0
for i=1 to length(s) do
switch s[i]
case '[': level += 1
case ']': level -= 1
if level<0 then exit end if
end switch
end for
return (level=0)
end function
sequence s
constant ok = {"not ok","ok"}
for i=1 to 10 do
for j=1 to 2 do
s = shuffle(join(repeat("[]",i-1),""))
printf(1,"%s %s\n",{s,ok[check_brackets(s)+1]})
end for
end for

View file

@ -0,0 +1,26 @@
nr = 0
while nr < 10
nr += 1
test=generate(random(9)+1)
see "bracket string " + test + " is " + valid(test) + nl
end
func generate n
l = 0 r = 0 output = ""
while l<n and r<n
switch random(2)
on 1 l+=1 output+="["
on 2 r+=1 output+="]"
off
end
if l=n output+=copy("]",n-r) else output+=copy("]",n-l) ok
return output
func valid q
count = 0
if len(q)=0 return "ok." ok
for x=1 to len(q)
if substr(q,x,1)="[" count+=1 else count-=1 ok
if count<0 return "not ok." ok
next
return "ok."

View file

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

View file

@ -0,0 +1,9 @@
import Foundation
func isBal(str: String) -> Bool {
var count = 0
return !str.characters.contains { ($0 == "[" ? ++count : --count) < 0 } && count == 0
}

View file

@ -0,0 +1,3 @@
isBal("[[[]]]") // true
isBal("[]][[]") // false

View file

@ -0,0 +1,13 @@
func randBrack(n: Int) -> String {
var bracks: [Character] = Array(Repeat(count: n, repeatedValue: "["))
for i in UInt32(n+1)...UInt32(n + n) {
bracks.insert("]", atIndex: Int(arc4random_uniform(i)))
}
return String(bracks)
}

View file

@ -0,0 +1 @@
randBrack(2) // "]][["

View file

@ -0,0 +1,12 @@
func randIsBal(n: Int) {
let (bal, un) = ("", "un")
for str in (1...n).map(randBrack) {
print("\(str) is \(isBal(str) ? bal : un)balanced\n")
}
}
randIsBal(4)

View file

@ -0,0 +1,7 @@
// ][ is unbalanced
//
// ]][[ is unbalanced
//
// []][[] is unbalanced
//
// [][][[]] is balanced

View file

@ -0,0 +1,37 @@
@Balanced[]s // each source must be started by specifying its file name; std extension .Ya could be ommitted and auto added by compiler
// all types are prefixed by `
// 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
`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
// 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