下面给出的设置数据:反向笛卡尔乘积
a | b | c | d
1 | 3 | 7 | 11
1 | 5 | 7 | 11
1 | 3 | 8 | 11
1 | 5 | 8 | 11
1 | 6 | 8 | 11
执行反向笛卡尔乘积得到:
a | b | c | d
1 | 3,5 | 7,8 | 11
1 | 6 | 8 | 11
我目前使用Scala的工作,和我的输入/输出数据类型是目前:
ListBuffer[Array[Array[Int]]]
我想出了一个解决方案(见下文),但觉得它可以优化。我愿意优化我的方法和全新的方法。在scala和c#中的解决方案是首选。
我也很好奇,如果这可以在MS SQL中完成。
我目前的解决方案:
def main(args: Array[String]): Unit = {
// Input
val data = ListBuffer(Array(Array(1), Array(3), Array(7), Array(11)),
Array(Array(1), Array(5), Array(7), Array(11)),
Array(Array(1), Array(3), Array(8), Array(11)),
Array(Array(1), Array(5), Array(8), Array(11)),
Array(Array(1), Array(6), Array(8), Array(11)))
reverseCartesianProduct(data)
}
def reverseCartesianProduct(input: ListBuffer[Array[Array[Int]]]): ListBuffer[Array[Array[Int]]] = {
val startIndex = input(0).size - 1
var results:ListBuffer[Array[Array[Int]]] = input
for (i <- startIndex to 0 by -1) {
results = groupForward(results, i, startIndex)
}
results
}
def groupForward(input: ListBuffer[Array[Array[Int]]], groupingIndex: Int, startIndex: Int): ListBuffer[Array[Array[Int]]] = {
if (startIndex < 0) {
val reduced = input.reduce((a, b) => {
mergeRows(a, b)
})
return ListBuffer(reduced)
}
val grouped = if (startIndex == groupingIndex) {
Map(0 -> input)
}
else {
groupOnIndex(input, startIndex)
}
val results = grouped.flatMap{
case (index, values: ListBuffer[Array[Array[Int]]]) =>
groupForward(values, groupingIndex, startIndex - 1)
}
results.to[ListBuffer]
}
def groupOnIndex(list: ListBuffer[Array[Array[Int]]], index: Int): Map[Int, ListBuffer[Array[Array[Int]]]] = {
var results = Map[Int, ListBuffer[Array[Array[Int]]]]()
list.foreach(a => {
val key = a(index).toList.hashCode()
if (!results.contains(key)) {
results += (key -> ListBuffer[Array[Array[Int]]]())
}
results(key) += a
})
results
}
def mergeRows(a: Array[Array[Int]], b: Array[Array[Int]]): Array[Array[Int]] = {
val zipped = a.zip(b)
val merged = zipped.map{ case (array1: Array[Int], array2: Array[Int]) =>
val m = array1 ++ array2
quickSort(m)
m.distinct
.array
}
merged
}
其工作原理是:
- 遍历列,从右到左(该groupingIndex指定上运行其列此列是唯一一个为了合并行而不必具有彼此相等的值)。
- 对所有其他列(不是groupingIndex)上的数据进行递归分组。
- 将所有列分组后,假定每个组中的数据在除分组列以外的每列中都有相同的值。
- 合并具有匹配列的行。为每一列取不同的值并对每一列进行排序。
我很抱歉,如果这些没有意义,我的大脑今天就不能运作。
答案必须是(1 | 3,5 | 7,8 | 11)联合(1 | 6 | 8 | 11)还是与其他答案同样好?ie(1 | 3,5 | 7 | 11)union(1 | 3,5,6 | 8 | 11),只要所有行都被覆盖一次?要找到最佳答案实际上是一项非常艰巨的任务,np-hard,请在这里查看答案:https://cs.stackexchange.com/questions/87247/reverse-cartesian-product-matching-all-given-rows – jbilander