Created
July 11, 2024 16:42
-
-
Save penguoir/0cdd24c8d4a19f45c346f82ec02563f8 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 Partition | |
include Enumerable | |
attr_reader :arr, :k | |
def initialize(arr, k) | |
@arr = arr | |
@k = k | |
end | |
def each | |
all_partitions(@arr) { |partition| yield partition } | |
end | |
private | |
def partition_set(set, index, ans, &block) | |
if index == set.size | |
yield ans.map(&:dup) if ans.size <= @k | |
return | |
end | |
ans.each do |subset| | |
subset << set[index] | |
partition_set(set, index + 1, ans, &block) | |
subset.pop | |
end | |
ans << [ set[index] ] | |
partition_set(set, index + 1, ans, &block) | |
ans.pop | |
end | |
def all_partitions(set, &block) | |
partition_set(set, 0, [], &block) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment