Last active
February 11, 2017 12:23
-
-
Save denpatin/137f6ba9df8259bb34fbf2087dda7fd0 to your computer and use it in GitHub Desktop.
Finding all increasing subsequences in Ruby
This file contains hidden or 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 powersets | |
inject([[]]){ |ps, el| ps + ps.map{ |e| e + [el] } } | |
end | |
def increasing? | |
each_with_index do |el, i| | |
break if i == size - 1 | |
return false unless el < self[i + 1] | |
end | |
true | |
end | |
def all_increasing_subsequences | |
powersets[1..-1].select(&:increasing?).sort_by(&:length) | |
end | |
def sequences | |
(0...size).flat_map { |i| (i...size).map { |j| self[i..j] } } | |
end | |
def sole? | |
size == 1 | |
end | |
def monotonic? | |
each_with_index do |el, i| | |
break if i == size - 1 | |
return false unless el == self[i + 1] - 1 | |
end | |
true | |
end | |
def monotonic_increasing_sequences | |
sequences.reject(&:sole?).select(&:monotonic?).sort_by(&:size).uniq.reverse! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment