2011-06-30 83 views
2

得到uniq的片我有什麼紅寶石,從組合

a = [1,2,3,4] 
=> [1, 2, 3, 4] 

b = a.combination(2).to_a 
=> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 

b.each_slice(2).to_a 
=> [[[1, 2], [1, 3]], [[1, 4], [2, 3]], [[2, 4], [3, 4]]] 

我試圖做到的,是一個獨特的組合

=> [[[1, 2], [3, 4]], [[1, 4], [2, 3]], [[1, 3], [2, 4]]] 

我試圖與置換,壓平,&℃。但無法找到魔力紅寶石代碼!

編輯:

上述答案是像

b = a.combination(2).to_a 
=> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 

爲了更精確。

a = [1,2,3,4,5,6] 

如何獲得

=> [[[1, 2], [3, 4], [5, 6]], [[1, 3], [2, 5], [4, 6]], [[1, 4], [2, 6], [3, 5]], [[1, 5], [2, 4], [3, 6]], [[1, 6], [2, 3], [4, 5]]] 

是uniq的值的5門陣列(1,2,3,4,5,6):

[1, 2], [3, 4], [5, 6] 
[1, 3], [2, 5], [4, 6] 
[1, 4], [2, 6], [3, 5] 
[1, 5], [2, 4], [3, 6] 
[1, 6], [2, 3], [4, 5] 

你似乎已經改變了這個問題。最初你想要一個數組數組,每個數組都有一對數組。現在你想要三胞胎嗎?

是的,因爲[1,2,3,4]的第一個例子太容易了,答案不適合更復雜的數組,如[1,2,3,4,5, 6]等等。

+0

這個問題非常模糊。 – sawa

+0

你似乎已經改變了這個問題。最初你想要一個數組數組,每個數組都有一對數組。現在你想要三胞胎嗎? – Andy

回答

0

最後我發現沒有置換,uniq的,組合的解決方案,壓平:)

a = [1,2,3,4,5,6] 
    count = a.count 

    totalloop = count - 1 
    arrayperloop = count/2 
    rounds = [] 

    for round in 0...totalloop 
     for i in 0...arrayperloop 

      x = (round + i) % (count - 1) 
      y = (count - 1 - i + round) % (count - 1) 

      if i == 0 
       y = count - 1 
      end 

      rounds<<[x + 1, y + 1] 
     end 
    end 

輪.each_slice(arrayperloop).to_a給我我想要的東西

[[[1, 6], [2, 5], [3, 4]], [[2, 6], [3, 1], [4, 5]], [[3, 6], [4, 2], [5, 1]], [[4, 6], [5, 3], [1, 2]], [[5, 6], [1, 4], [2, 3]]] 

不是很難看!如果我們將n * 2整數加到數組中,總是會工作的。

+0

你不使用'a '。你可以用'count = 6'替換前兩行 – Andy

1

這讓你最那裏的方式,我認爲

[1,2,3,4].combination(2).inject([]){|arr,r| arr << (Hash[*r]); arr}

如果你從這個數組採取的第一個和最後一個元素迭代你得到你是什麼

def con(h, arr = []) 
    arr <<[h.delete(h.first).to_a.flatten, h.delete(h.last).to_a.flatten] 
    con(h, arr) unless h.empty? 
    p arr 
end 

#=> [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]] 
+0

這是美麗的廢話! – changelog

+0

方式酷 - 漂亮的小拼圖:-) – chrispanda

+0

這真的很聰明。但我不知道它爲什麼可行... – Andy

0

好後,它不漂亮,但它的工作原理。組合需要一個塊。

a = [1,2,3,4] 
ans = [] 

a.combination(2) do |i| 
    a.combination(2) do |j| 
    x = [i, j] 
    y = x.flatten 
    next if y.uniq != y 
    ans << x 
    end 
end 

puts ans.inspect 

編輯:讓它稍微不那麼難看。

0

增加了這個作爲另一個答案,因爲它是一個非常不同的問題 - 而且更難!

def accept(a) 
    0.upto(a.size-1){|i| return false unless a[i] == a[i].sort 
    return false if (i > 0 && a[i][0] <= a[i-1][0])} 
    true 
end 

x=[1,2,3,4,5,6].permutation.inject([]){|arr, per| arr<< per.in_groups_of(2); arr} 
arr = x.inject([]){|arr,y| arr << y if accept(y); arr} 
p arr 

不是很漂亮,但你想要做什麼陣列的任何尺寸的,我認爲

+0

這給了很多像[1,2]一樣的重複數組。我想要的就是這個數組uniq,就像我寫的例子一樣。 – highlight

+0

實際上,最後一行中的打印語句打印出你想要的東西 - 編輯以使其更清晰 - 詮釋控制檯,這是由輸出淹沒 – chrispanda

+0

現在清理它,所以它仍然更清晰 – chrispanda