Created
July 24, 2015 02:54
-
-
Save michaelfeathers/037b4785425a86b23efa 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
class Array | |
def prefixes | |
result = [] | |
(0..size).each {|n| result << take(n) } | |
result | |
end | |
def indices value | |
map {|v| v == value ? 0 : 1 } | |
end | |
def negate | |
map {|v| v == 0 ? 1 : 0 } | |
end | |
def times ary | |
result = [] | |
each_with_index { |v,n| result << v * ary[n] } | |
result | |
end | |
def plus n | |
map {|v| v + n } | |
end | |
def group_on mask | |
return [] if size != mask.size | |
groups = {} | |
mask.each_with_index do |v,n| | |
(groups[v] ||= []) << self[n] | |
end | |
groups.values | |
end | |
end | |
class String | |
def to_a; chars.to_a; end | |
end | |
def words text | |
rep = ' ' + text | |
letters_mask = rep.to_a.indices(' ') | |
spaces_mask = letters_mask.negate | |
keys_mask = letters_mask.times(spaces_mask.prefixes.map {|v| v.reduce(0,:+) }.plus(1)) | |
rep.to_a.group_on(keys_mask).drop(1).map(&:join) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment