2014-02-21 46 views
0

令人煩惱的是,這個問題很容易,但今天一直令我頭痛。 (道歉的僞代碼)布爾數組的所有組合

說我們有布爾,a和兩個數組列表b其中:

a = [true, true, false]

b = [true, false, true]

我想產生的所有組合的列表ab之間的比較與以下規則:

  • 如果a[i] = trueb[i] = true產生的result[i]應該總是返回true
  • 如果a[i] = falseb[i] = false總是返回false
  • 如果a[i] != b[i]返回列表,其中一個result[i]true而另一個是false

所以對於compare(a,b)預期的結果將是(我希望...):

[true, true, false], 
[true, false, false], 
[true, true, true], 
[true, false, true] 

我試圖做到這一點在Java中,但似乎無法正常循環,任何人都可以給我一些幫助?

編輯:

另一個簡單的例子,對於規則3:

a = [true, false] 
b = [false, true] 

results: 

[true, false] 
[false, true] 
[true, true] 
[false, false] 

基本上這就是我的意思:)

+1

應該不是最後一個是'[真,假,真]'? –

+0

不能理解輸出。它不能正確。 false + true = false,false + false = false,false + true = false,true + false = false,true + false = false。如果將數組a中的每個元素與數組b中的每個元素相結合,則會得到5次錯誤。但你的輸出只顯示4次。 – kai

+0

3^2 +數組a的給出了兩次列表,並且數組a的兩個真都給出了一個列表,所以在結果中有13個值不是12。 – kai

回答

1

遞歸是解決這類組合問題的經典方法。

void resursivelyCombine(List<List<Boolean>> result, List<Boolean> current, List<Boolean> in1, List<Boolean> in2, int index) { 
    if (index == in1.size()) { 
     result.add(current); 
    } else { 
     if (in1.get(index).equals(in2.get(index))) { 
      current.add(in1.get(index)); 
      recursivelyCombine(result, current, in1, in2, index+1); 
     } else { 
      List<Boolean> temp = new ArrayList<>(current); 
      temp.add(Boolean.TRUE); 
      recursivelyCombine(result, temp, in1, in2, index+1); 

      temp = new ArrayList<>(current); 
      temp.add(Boolean.FALSE); 
      recursivelyCombine(result, temp, in1, in2, index+1); 
     } 
    } 
} 

類似的東西:)代碼可能需要一點整理,因爲我只是在這裏輸入它未經測試。

這樣稱呼它:

List<List<Boolean>> results = new ArrayList<>(); 
recursivelyCombine(results, new ArrayList<Boolean>(), in1, in2, 0); 
+0

我還沒有測試這個徹底,但它似乎你明白我在試圖穿過!這看起來幾乎肯定是正確的解決方案,但一旦證實我會回覆給你,並將答案標記爲接受,如果適用的話:) –

2

我想說的遞歸。我不知道什麼是你的目標在性能和多長時間將是數組,但我會做類似如下:

1,步驟:創建一個數組,其中一些元素是固定的,一些被標記爲您的規則,這樣的曖昧:

[Boolean.True, null, null] 

這意味着那裏是null應該是true 假。

2,步驟:在用於null的最後一次出現的方法搜索,將其改爲Boolean.True並調用與該陣列的方法相同。在下一行中將其更改爲Boolean.False並再次調用相同的方法。在這個新的調用中,將會有一個更少的空元素,並且您在模糊空間中獲得了具有Boolean.TrueBoolean.False元素的數組。

3,步驟:在該方法中,還檢查數組中是否不存在更多null值,如果沒有,則將其寫入輸出。

當然不是Booleannull值,你可以使用別的或更有意義的對象,你也可以以迭代的方式做到這一點,但我不知道你的問題的細節。

希望我能幫上忙。