Created
August 15, 2015 02:27
-
-
Save gdejohn/e3803f3e34eab9c17a5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ceylon.collection {ArrayList} | |
import ceylon.math.float {random} | |
shared void run() { | |
value brackets = String(shuffle("[]".repeat(3))); | |
print(brackets + " " + (balanced(brackets) then "OK" else "NOT OK")); | |
} | |
Boolean balanced(String brackets) | |
=> brackets.scan(0)((x, y) => x + (y == '[' then 1 else -1)).every(0.notLargerThan); | |
Iterable<Element, Absent> shuffle<Element, Absent>(Iterable<Element, Absent> elements) | |
given Absent satisfies Null => object satisfies Iterable<Element, Absent> { | |
value list = ArrayList{*elements}; | |
iterator() => object satisfies Iterator<Element> { | |
variable value index = list.size; | |
shared actual Element|Finished next() { | |
value randomIndex = (random() * index--).integer; | |
if (exists element = list[index]) { | |
assert (exists randomElement = list[randomIndex]); | |
list.set(index, randomElement); | |
list.set(randomIndex, element); | |
return randomElement; | |
} | |
return finished; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment