How to compare each item in a list with the rest, only once?

后端 未结 5 513
误落风尘
误落风尘 2020-12-07 09:02

Say I have an array/list of things I want to compare. In languages I am more familiar with, I would do something like

for (int i = 0, i < mylist.size(); i         


        
5条回答
  •  既然无缘
    2020-12-07 09:34

    Your solution is correct, but your outer loop is still longer than needed. You don't need to compare the last element with anything else because it's been already compared with all the others in the previous iterations. Your inner loop still prevents that, but since we're talking about collision detection you can save the unnecessary check.

    Using the same language you used to illustrate your algorithm, you'd come with something like this:

    for (int i = 0, i < mylist.size() - 1; ++i)
        for (int j = i + 1, j < mylist.size(); --j)
            compare(mylist[i], mylist[j])
    

提交回复
热议问题