Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinking/cad87440cfda9417c115 to your computer and use it in GitHub Desktop.
Save gavinking/cad87440cfda9417c115 to your computer and use it in GitHub Desktop.
my version of @luolong's solution to Rosetta Code balanced brackets
shared void balancedBrackets() {
value nextRandom = random();
for (length in 1..10) {
value text = generate(nextRandom, length);
print("``text.padTrailing(20)`` - ``if (balanced(text)) then "OK" else "NOT OK"``");
}
}
Boolean balanced(String input)
=> !input
.map((ch) => switch (ch) case('[') 1 case (']') -1 else 0)
.scan(0)(plus)
.any(Integer.negative);
String generate(Integer() nextRandom, Integer length)
=> let (jumbled =
"[]".repeat(length)
.map((ch) => nextRandom() % length -> ch)
.sort(increasingKey)
.map(Entry.item))
String(jumbled);
Integer random(variable Integer seed
= system.nanoseconds + system.milliseconds)() {
seed = seed.xor(seed.rightLogicalShift(12));
seed = seed.xor(seed.leftLogicalShift(25));
seed = seed.xor(seed.rightLogicalShift(27));
return seed * 2685821657736338717;
}
@luolong
Copy link

luolong commented Aug 17, 2015

hmmh..
Do I understand this correctly, that declaring input argument seed as variable in method declaration will cause the random() method to become stateful?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment