Skip to content

Instantly share code, notes, and snippets.

@AnhNhan
Last active August 29, 2015 14:14
Show Gist options
  • Save AnhNhan/684232ac49968838f16a to your computer and use it in GitHub Desktop.
Save AnhNhan/684232ac49968838f16a to your computer and use it in GitHub Desktop.
import ceylon.collection {
group
}
import ceylon.test {
assertEquals,
test
}
{String*} splitBy(Boolean(Character) predicate)(String input)
=> input.split(predicate);
"Turns a function accepting two parameters into a function accepting an
entry/pair. In other words:
Return(Key, Item)
gets transformed into
Return(Key->Item)"
shared Return acceptEntry<Return, Key, Item>(Callable<Return, [Key, Item]> callable)(Entry<Key, Item> entry)
given Key satisfies Object
=> callable(entry.key, entry.item);
Callable<Return, Args> pipe2<Return, Between, Args>(Callable<Between, Args> first, Callable<Return, [Between]> second)
given Args satisfies Anything[]
=> flatten((Args args) => second(first(*args)));
Map<T, [T+]> duplicates<T>({T*} input)
given T satisfies Object
=> group(input, identity<T>);
"One-sided canceling of letters. Returns the letters that haven't been canceled.
Kinda like PHP's array_diff. Apply it in both directions.
Note that the order of the non-canceled letter may be arbitrary. Currently it's
*maybe* sorted alphabetically. Don't count on it."
Character[] cancelLetters(String left, String right)
{
value lefts = duplicates(left);
value rights = duplicates(right);
return lefts.flatMap(acceptEntry((Character char, [Character+] chars) => {char}.repeat(chars.size - (rights[char]?.size else 0)))).sequence();
}
test
void testCancelLetters()
{
assertEquals(cancelLetters("", ""), []);
assertEquals(cancelLetters("hat", "hat"), []);
assertEquals(cancelLetters("hat", "cat"), ['h']);
assertEquals(cancelLetters("cat", "hat"), ['c']);
assertEquals(cancelLetters("hiss", "miss"), ['h']);
assertEquals(cancelLetters("miss", "hiss"), ['m']);
assertEquals(cancelLetters("because", "cause"), ['b', 'e']);
assertEquals(cancelLetters("cause", "because"), []);
assertEquals(cancelLetters("hello", "below"), ['h', 'l']);
assertEquals(cancelLetters("below", "hello"), ['b', 'w']);
}
[Character[], Character[]] wordsWithEnemiesEasyScore(String left, String right)
=> [cancelLetters(left, right), cancelLetters(right, left)];
test
void testEasy198()
{
value inputs = {
"because cause",
"hello below",
"hit miss",
"rekt pwn",
"combo jumbo",
"critical optical",
"isoenzyme apoenzyme",
"tribesman brainstem",
"blames nimble",
"yakuza wizard",
"longbow blowup"
};
value values = inputs.map(pipe2(splitBy(' '.equals), ({String*} strs) => [strs.getFromFirst(0) else nothing, strs.getFromFirst(1) else nothing]));
value results = values.map(unflatten(wordsWithEnemiesEasyScore));
results.collect(print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment