Implementing an algorithm that matches lids to jars of the correct size

爱⌒轻易说出口 提交于 2020-01-25 06:46:14

问题


The problem: We're given a list of jars and a list of lids (same size). For each jar, there is at least one matching lid and vice versa. In the lists that are given, both the lids and jars are scrambled randomly. I want to find an efficient algorithm to return pairs of matching lids and jars.

My strategy: sort both sets, using an efficient algorithm (log(n), n = number of jars = numbers of lids). Then we can just match them two-by-two into a pair, which we add to a list that will be the resulting output.

Only restriction: jars cannot be compared to jars and lids cannot be compared to lids. A comparison between jars and lids is possible to make (jar.compareTo(lid) or lid.compareTo(jar)).

Idea: (QuickSort) Choose a pivotal jar and divide the lids into three groups: 1) The lids that are too small for the chosen reference lid, 2) the lid that matches this lid (there is at least one such lid), 3) the lids that are too large for the chosen pivot. Making new list for these subgroups is not recommended (just like in QuickSort), so we partition the lids via successive swaps (Collections have a swap method).

I believe that we can just select a random pivotal lid to partition the jars in a similar way. Now, I think that recursion could be a possibility to sort the sublist that we have formed.

As simple as this strategy may sound, the implementation turned out not to be so trivial. I actually don't even know where to start. Do I need to seperate methods for the recursive calls in the sublists? How can I do all of this without using f.ex. copyOfRange (i.e. copying a subset of the given lists)? Is there a related graph theoretical problem, that already has an existing implementation?

Thank you in advance!


回答1:


This site does a great job explaining how to implement QuickSort. It even contains an implementation.

Some of the points from the website are:

Your partition method will only partition the section of the array you specify, so you don't need to make a copy using copyOfRange. When it starts you partition the whole array, then partition the part before and the part after the pivot using recursion.

You can use a random pivot. Since it doesn't really make a difference, you could also forgo the random part and simply use the first element of the array.



来源:https://stackoverflow.com/questions/58597613/implementing-an-algorithm-that-matches-lids-to-jars-of-the-correct-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!