Skip to content

Instantly share code, notes, and snippets.

@0x0dea

0x0dea/muggle.rb Secret

Created July 5, 2015 08:49
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 0x0dea/4178cbfe1729e989e564 to your computer and use it in GitHub Desktop.
Save 0x0dea/4178cbfe1729e989e564 to your computer and use it in GitHub Desktop.
@_,$_,@__=->_,__{_==''?_:(__[_[$_-$_]]?_[$_-$_]:'')+@_[_[$_..-$_],__]},$$/$$,->_{__,___=_[$_-$_],_[$_..-$_];_==''?_:@__[@_[___,->_{_<__}]]+__+@__[@_[___,->_{_>=__}]]};($__=->*_{__=@__[_[$.]];$*[$_-$_]==__ ?_:$*<<__;_[$.+=$_]?$__[*_]:!$*[$_]})['allergy', 'gallery', 'largely', 'regally']
# The opening variables were defined in parallel to increase confusion, so let's undo that.
$_ = $$ /$$ # 1, because we'll need -1, 0, and 1.
# @_ = ->_,__{_==''?_:(__[_[$_-$_]]?_[$_-$_]:'')+@_[_[$_..-$_],__]}
# @_ is a string filter:
# @_ = ->_,__{
filter = -> str, pred {
# _==''?_:
str == '' ? str : # If empty, nothing to filter; return. Otherwise,
# (__[_[$_-$_]]?_[$_-$_]:'')+
(pred[str[0]] ? str[0] : '') + # keep the head only if it satisfies the predicate
# @_[_[$_..-$_],__]}
filter[str[1..-1], pred] # and add it to the filter applied to the tail.
}
# @__=->_{__,___=_[$_-$_],_[$_..-$_];_==''?_:@__[@_[___,->_{_<__}]]+__+@__[@_[___,->_{_>=__}]]}
# @__ is ex-situ Quicksort:
# @__=->_{
sort = -> str {
# __,___=_[$_-$_],_[$_..-$_];
pivot, rest = str[0], str[1..-1] # Head used as pivot for simplicity.
# _==''?_:
str == '' ? str : # If empty, nothing to sort; return. Otherwise,
# @__[@_[___,->_{_<__}]]+
sort[filter[rest, -> chr {chr < pivot}]] + # Concatenate the sorted lesser characters
# __+
pivot + # with the pivot
# @__[@_[___,->_{_>=__}]]}
sort[filter[rest, -> chr {chr >= pivot}]] # and the sorted greater-or-equal characters.
}
uniqs = $* # ARGV, used as an initially empty pseudo-set.
index = $. # ARGF.lineno, 0 at program start.
# $__=->*_{__=@__[_[$.]];$*[$_-$_]==__ ?_:$*<<__;_[$.+=$_]?$__[*_]:!$*[$_]}
# $__ is all_anagrams:
# $__=->*_{
all_anagrams = -> *words {
# __=@__[_[$.]];
sorted = sort[words[index]]
# $*[$_-$_]==__ ?_:$*<<__;
uniqs[0] == sorted ? 0 : uniqs << sorted # Add the sorted word if it's new.
# _[$.+=$_]?
words[index += 1] ? # If there is another word to consume,
# $__[*_]:
all_anagrams[*words] : # go again with the increased index. Otherwise,
# !$*[$_]}
!uniqs[1] # the arguments were anagrams if uniqs is of length 1.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment