Created
June 21, 2016 15:12
-
-
Save honake/b685811d7644c563cd26a620274a75e6 to your computer and use it in GitHub Desktop.
kind_of_fair_combination.rb
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 fair_combination | |
arr = [] | |
n = length | |
m = (n / 2).floor | |
# Divide by interval | |
(1..m - 1).each do |j| | |
subarr = (0..n - 1).to_a | |
sub1 = [] | |
sub2 = [] | |
begin | |
j.times { sub1.push(subarr.shift) unless subarr.empty? } | |
j.times { sub2.push(subarr.shift) unless subarr.empty? } | |
end until subarr.empty? | |
sub1.concat(sub2).each do |sub| | |
arr.push([self[sub], self[(sub + j).modulo(n)]]) | |
end | |
end | |
# Try to extend for even case | |
if n.even? | |
(0..(n / 2) - 1).each do |i| | |
arr.push([self[i], self[(i + (n / 2)).modulo(n)]]) | |
end | |
else | |
(0..n - 1).each do |i| | |
arr.push([self[i], self[(i + m).modulo(n)]]) | |
end | |
end | |
arr | |
end | |
end | |
# p (1..7).to_a.fair_combination | |
# --> [[1, 2], [3, 4], [5, 6], [7, 1], [2, 3], [4, 5], [6, 7], [1, 3], [2, 4], [5, 7], [6, 1], [3, 5], [4, 6], [7, 2], [1, 4], [2, 5], [3, 6], [4, 7], [5, 1], [6, 2], [7, 3]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment