Skip to content

Commit

Permalink
perf: 优化列表操作预测算法
Browse files Browse the repository at this point in the history
  • Loading branch information
xz-dev committed Sep 22, 2020
1 parent b6ab52a commit 55a4dfd
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions app/src/main/java/net/xzos/upgradeall/utils/ListUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,46 @@ fun <E> list1ToList2(list1: List<E>, list2: List<E>): List<ListOperationStepBase
}
val tmpList = list1.toMutableList()
val operationSteps = mutableListOf<ListOperationStepBase>()
// 删除多余项
for (item in delList) {
val index = tmpList.indexOf(item)
operationSteps.add(ListDelOperationStep(index))
tmpList.removeAt(index)
}
// 添加缺失项
val addItemMap = hashMapOf<E, Int>()
for (item in addList) {
val index = list2.indexOf(item)
if (index < tmpList.size) {
tmpList.add(index, item)
operationSteps.add(ListAddOperationStep(index, item))
addItemMap[item] = index
} else {
tmpList.add(item)
operationSteps.add(ListAddOperationStep(tmpList.size - 1, item))
addItemMap[item] = tmpList.size - 1
}
}
// 还原位置
val swapItemMap = mutableMapOf<E, Pair<Int, Int>>()
for (i in tmpList.indices) {
val item = tmpList[i]
val newIndex = list2.indexOf(item)
if (i != newIndex && newIndex < tmpList.size) {
if (i != newIndex) {
tmpList[i] = tmpList[newIndex].also { tmpList[newIndex] = tmpList[i] }
operationSteps.add((ListSwapOperationStep(i, newIndex)))
if (item in addItemMap) {
addItemMap[item] = newIndex
} else {
swapItemMap[item]?.let {
swapItemMap[item] = Pair(it.first, newIndex)
} ?: run { swapItemMap[item] = Pair(i, newIndex) }
}
}
}
val sorted = addItemMap.toList().sortedBy { (_, value) -> value }.toMap()
for ((item, index) in sorted.entries) {
operationSteps.add(ListAddOperationStep(index, item))
}
for ((_, index) in swapItemMap) {
operationSteps.add((ListSwapOperationStep(index.first, index.second)))
}
return operationSteps
}
}

0 comments on commit 55a4dfd

Please sign in to comment.