[â) and closing brackets (â]â), in some arbitrary order.
+* 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.
+
+'''Examples''':
+
+ (empty) OK
+ [] OK ][ NOT OK
+ [][] OK ][][ NOT OK
+ [[][]] OK []][[] NOT OK
diff --git a/Task/Balanced_brackets/AWK/balanced_brackets.awk b/Task/Balanced_brackets/AWK/balanced_brackets.awk
new file mode 100644
index 0000000000..e6b151f39e
--- /dev/null
+++ b/Task/Balanced_brackets/AWK/balanced_brackets.awk
@@ -0,0 +1,21 @@
+#!/usr/bin/awk -f
+BEGIN {
+ print isbb("[]")
+ print isbb("][")
+ print isbb("][][")
+ print isbb("[][]")
+ print isbb("[][][]")
+ print isbb("[]][[]")
+}
+
+function isbb(x) {
+ s = 0;
+ for (k=1; k<=length(x); k++) {
+ c = substr(x,k,1);
+ if (c=="[") {s++;}
+ else { if (c=="]") s--; }
+
+ if (s<0) {return 0};
+ }
+ return (s==0);
+}
diff --git a/Task/Balanced_brackets/BASIC/balanced_brackets.bas b/Task/Balanced_brackets/BASIC/balanced_brackets.bas
new file mode 100644
index 0000000000..ffc201be3e
--- /dev/null
+++ b/Task/Balanced_brackets/BASIC/balanced_brackets.bas
@@ -0,0 +1,57 @@
+DECLARE FUNCTION checkBrackets% (brackets AS STRING)
+DECLARE FUNCTION generator$ (length AS INTEGER)
+
+RANDOMIZE TIMER
+
+DO
+ x$ = generator$ (10)
+ PRINT x$,
+ IF checkBrackets(x$) THEN
+ PRINT "OK"
+ ELSE
+ PRINT "NOT OK"
+ END IF
+LOOP WHILE LEN(x$)
+
+FUNCTION checkBrackets% (brackets AS STRING)
+ 'returns -1 (TRUE) if everything's ok, 0 (FALSE) if not
+ DIM L0 AS INTEGER, sum AS INTEGER
+
+ FOR L0 = 1 TO LEN(brackets)
+ SELECT CASE MID$(brackets, L0, 1)
+ CASE "["
+ sum = sum + 1
+ CASE "]"
+ sum = sum - 1
+ END SELECT
+ IF sum < 0 THEN
+ checkBrackets% = 0
+ EXIT FUNCTION
+ END IF
+ NEXT
+
+ IF 0 = sum THEN
+ checkBrackets% = -1
+ ELSE
+ checkBrackets% = 0
+ END IF
+END FUNCTION
+
+FUNCTION generator$ (length AS INTEGER)
+ z = INT(RND * length)
+ IF z < 1 THEN generator$ = "": EXIT FUNCTION
+ REDIM x(z * 2) AS STRING
+ FOR i = 0 TO z STEP 2
+ x(i) = "["
+ x(i + 1) = "]"
+ NEXT
+ FOR i = 1 TO UBOUND(x)
+ z = INT(RND * 2)
+ IF z THEN SWAP x(i), x(i - 1)
+ NEXT
+ xx$ = ""
+ FOR i = 0 TO UBOUND(x)
+ xx$ = xx$ + x(i)
+ NEXT
+ generator$ = xx$
+END FUNCTION
diff --git a/Task/Balanced_brackets/Befunge/balanced_brackets.bf b/Task/Balanced_brackets/Befunge/balanced_brackets.bf
new file mode 100644
index 0000000000..2264f098e0
--- /dev/null
+++ b/Task/Balanced_brackets/Befunge/balanced_brackets.bf
@@ -0,0 +1,7 @@
+v > "KO TON" ,,,,,, v
+> ~ : 25*- #v_ $ | > 25*, @
+ > "KO" ,, ^
+ > : 1991+*+- #v_ v
+ > \ : 1991+*+- #v_v
+ \ $
+^ < <$<
diff --git a/Task/Balanced_brackets/C/balanced_brackets-2.c b/Task/Balanced_brackets/C/balanced_brackets-2.c
new file mode 100644
index 0000000000..3bf22f21e3
--- /dev/null
+++ b/Task/Balanced_brackets/C/balanced_brackets-2.c
@@ -0,0 +1,9 @@
+'': True
+'[]': True
+']][[': False
+'[][][]': True
+'[]][[]][': False
+'[]][[[[]]]': False
+']]]][[[]][[[': False
+']]]]]][][[[[[[': False
+'[][]][[][[[]]][]': False
diff --git a/Task/Balanced_brackets/C/balanced_brackets.c b/Task/Balanced_brackets/C/balanced_brackets.c
new file mode 100644
index 0000000000..3427dcb738
--- /dev/null
+++ b/Task/Balanced_brackets/C/balanced_brackets.c
@@ -0,0 +1,43 @@
+#includetree, eetr, (0)
+
+A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
+
+The words to test with are: abracadabra, seesaw, elk, grrrrrr, up, a
+
+;Cf.
+* [[Anagrams/Deranged anagrams]]
+* [[Permutations/Derangements]]
diff --git a/Task/Best_shuffle/AWK/best_shuffle-2.awk b/Task/Best_shuffle/AWK/best_shuffle-2.awk
new file mode 100644
index 0000000000..e3c0ed677e
--- /dev/null
+++ b/Task/Best_shuffle/AWK/best_shuffle-2.awk
@@ -0,0 +1,79 @@
+# out["string"] = best shuffle of string _s_
+# out["score"] = number of matching characters
+function best_shuffle(out, s, c, i, j, k, klen, p, pos, set, rlen, slen) {
+ slen = length(s)
+ for (i = 1; i <= slen; i++) {
+ c = substr(s, i, 1)
+
+ # _set_ of all characters in _s_, with count
+ set[c] += 1
+
+ # _pos_ classifies positions by letter,
+ # such that pos[c, 1], pos[c, 2], ..., pos[c, set[c]]
+ # are the positions of _c_ in _s_.
+ pos[c, set[c]] = i
+ }
+
+ # k[1], k[2], ..., k[klen] sorts letters from low to high count
+ klen = 0
+ for (c in set) {
+ # insert _c_ into _k_
+ i = 1
+ while (i <= klen && set[k[i]] <= set[c])
+ i++ # find _i_ to sort by insertion
+ for (j = klen; j >= i; j--)
+ k[j + 1] = k[j] # make room for k[i]
+ k[i] = c
+ klen++
+ }
+
+ # Fill pos[slen], ..., pos[3], pos[2], pos[1] with positions
+ # in the order that we want to fill them.
+ i = 1
+ while (i <= slen) {
+ for (j = 1; j <= klen; j++) {
+ c = k[j]
+ if (set[c] > 0) {
+ pos[i] = pos[c, set[c]]
+ i++
+ delete pos[c, set[c]]
+ set[c]--
+ }
+ }
+ }
+
+ # Now fill in _new_ with _letters_ according to each position
+ # in pos[slen], ..., pos[1], but skip ahead in _letters_
+ # if we can avoid matching characters that way.
+ rlen = split(s, letters, "")
+ for (i = slen; i >= 1; i--) {
+ j = 1
+ p = pos[i]
+ while (letters[j] == substr(s, p, 1) && j < rlen)
+ j++
+ for (new[p] = letters[j]; j < rlen; j++)
+ letters[j] = letters[j + 1]
+ delete letters[rlen]
+ rlen--
+ }
+
+ out["string"] = ""
+ for (i = 1; i <= slen; i++) {
+ out["string"] = out["string"] new[i]
+ }
+
+ out["score"] = 0
+ for (i = 1; i <= slen; i++) {
+ if (new[i] == substr(s, i, 1))
+ out["score"]++
+ }
+}
+
+BEGIN {
+ count = split("abracadabra seesaw elk grrrrrr up a", words)
+ for (i = 1; i <= count; i++) {
+ best_shuffle(result, words[i])
+ printf "%s, %s, (%d)\n",
+ words[i], result["string"], result["score"]
+ }
+}
diff --git a/Task/Best_shuffle/AWK/best_shuffle-3.awk b/Task/Best_shuffle/AWK/best_shuffle-3.awk
new file mode 100644
index 0000000000..8f7f2ee690
--- /dev/null
+++ b/Task/Best_shuffle/AWK/best_shuffle-3.awk
@@ -0,0 +1,7 @@
+$ awk -f best-shuffle.awk
+abracadabra, baarrcadaab, (0)
+seesaw, essewa, (0)
+elk, kel, (0)
+grrrrrr, rgrrrrr, (5)
+up, pu, (0)
+a, a, (1)
diff --git a/Task/Best_shuffle/AWK/best_shuffle.awk b/Task/Best_shuffle/AWK/best_shuffle.awk
new file mode 100644
index 0000000000..31cec9f821
--- /dev/null
+++ b/Task/Best_shuffle/AWK/best_shuffle.awk
@@ -0,0 +1,40 @@
+{
+ scram = best_shuffle($0)
+ print $0 " -> " scram " (" unchanged($0, scram) ")"
+}
+
+function best_shuffle(s, c, i, j, len, r, t) {
+ len = split(s, t, "")
+
+ # Swap elements of t[] to get a best shuffle.
+ for (i = 1; i <= len; i++) {
+ for (j = 1; j <= len; j++) {
+ # Swap t[i] and t[j] if they will not match
+ # the original characters from s.
+ if (i != j &&
+ t[i] != substr(s, j, 1) &&
+ substr(s, i, 1) != t[j]) {
+ c = t[i]
+ t[i] = t[j]
+ t[j] = c
+ break
+ }
+ }
+ }
+
+ # Join t[] into one string.
+ r = ""
+ for (i = 1; i <= len; i++)
+ r = r t[i]
+ return r
+}
+
+function unchanged(s1, s2, count, len) {
+ count = 0
+ len = length(s1)
+ for (i = 1; i <= len; i++) {
+ if (substr(s1, i, 1) == substr(s2, i, 1))
+ count++
+ }
+ return count
+}
diff --git a/Task/Best_shuffle/C/best_shuffle-2.c b/Task/Best_shuffle/C/best_shuffle-2.c
new file mode 100644
index 0000000000..d210eda6e9
--- /dev/null
+++ b/Task/Best_shuffle/C/best_shuffle-2.c
@@ -0,0 +1,106 @@
+#include high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
+* change high = N-1 to high = N
+* change high = mid-1 to high = mid
+* (for recursive algorithm) change if (high < low) to if (high <= low)
+* (for iterative algorithm) change while (low <= high) to while (low < high)
+
+; Traditional algorithm
+The algorithms are as follows (from [[wp:Binary search|Wikipedia]]). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
+
+'''Recursive Pseudocode''':
+ // initially called with low = 0, high = N-1
+ BinarySearch(A[0..N-1], value, low, high) {
+ // invariants: value > A[i] for all i < low
+ value < A[i] for all i > high
+ if (high < low)
+ return not_found // value would be inserted at index "low"
+ mid = (low + high) / 2
+ if (A[mid] > value)
+ return BinarySearch(A, value, low, mid-1)
+ else if (A[mid] < value)
+ return BinarySearch(A, value, mid+1, high)
+ else
+ return mid
+ }
+
+'''Iterative Pseudocode''':
+ BinarySearch(A[0..N-1], value) {
+ low = 0
+ high = N - 1
+ while (low <= high) {
+ // invariants: value > A[i] for all i < low
+ value < A[i] for all i > high
+ mid = (low + high) / 2
+ if (A[mid] > value)
+ high = mid - 1
+ else if (A[mid] < value)
+ low = mid + 1
+ else
+ return mid
+ }
+ return not_found // value would be inserted at index "low"
+ }
+
+; Leftmost insertion point
+The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
+
+'''Recursive Pseudocode''':
+ // initially called with low = 0, high = N - 1
+ BinarySearch_Left(A[0..N-1], value, low, high) {
+ // invariants: value > A[i] for all i < low
+ value <= A[i] for all i > high
+ if (high < low)
+ return low
+ mid = (low + high) / 2
+ if (A[mid] >= value)
+ return BinarySearch_Left(A, value, low, mid-1)
+ else
+ return BinarySearch_Left(A, value, mid+1, high)
+ }
+
+'''Iterative Pseudocode''':
+ BinarySearch_Left(A[0..N-1], value) {
+ low = 0
+ high = N - 1
+ while (low <= high) {
+ // invariants: value > A[i] for all i < low
+ value <= A[i] for all i > high
+ mid = (low + high) / 2
+ if (A[mid] >= value)
+ high = mid - 1
+ else
+ low = mid + 1
+ }
+ return low
+ }
+
+; Rightmost insertion point
+The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
+
+'''Recursive Pseudocode''':
+ // initially called with low = 0, high = N - 1
+ BinarySearch_Right(A[0..N-1], value, low, high) {
+ // invariants: value >= A[i] for all i < low
+ value < A[i] for all i > high
+ if (high < low)
+ return low
+ mid = (low + high) / 2
+ if (A[mid] > value)
+ return BinarySearch_Right(A, value, low, mid-1)
+ else
+ return BinarySearch_Right(A, value, mid+1, high)
+ }
+
+'''Iterative Pseudocode''':
+ BinarySearch_Right(A[0..N-1], value) {
+ low = 0
+ high = N - 1
+ while (low <= high) {
+ // invariants: value >= A[i] for all i < low
+ value < A[i] for all i > high
+ mid = (low + high) / 2
+ if (A[mid] > value)
+ high = mid - 1
+ else
+ low = mid + 1
+ }
+ return low
+ }
+
+;Extra credit
+Make sure it does not have overflow bugs.
+
+The line in the pseudocode above to calculate the mean of two integers:
+mid = (low + high) / 2+could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and
low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
+
+One way to fix it is to manually add half the range to the low number:
+mid = low + (high - low) / 2+Even though this is mathematically equivalent to the above, it is not susceptible to overflow. + +Another way for signed integers, possibly faster, is the following: +
mid = (low + high) >>> 1+where
>>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
+
+'''References:''' EMPTY
+ case TREE => if (neighbours(x, y).exists(_==BURNING)) BURNING
+ else if (Random.nextDouble