我应该使用哪种算法来排序学生?

Dre*_*rew 6 sorting algorithm lua grouping

在一个生成随机学生组的程序中,我给用户提供了强制将特定学生组合在一起并阻止学生配对的选项.我已经尝试了两天来制作我自己的算法来实现这一点,但是我在所有的递归中都迷失了.我正在Lua中创建程序,但我将能够理解任何类型的伪代码.以下是学生排序方式的示例:

students = {
    Student1 = {name=Student1, force={"Student2"}, deny={}};
    Student2 = {name=Student2, force={"Student1","Student3"}, deny={}};
    Student3 = {name=Student3, force={"Student2"}, deny={}};
}-- A second name property is given in the case that the student table needs to be accessed by students[num] to retrieve a name
Run Code Online (Sandbox Code Playgroud)

然后我创建临时表:

forced = {}--Every student who has at least 1 entry in their force table is placed here, even if they have 1 or more in the deny table
denied = {}--Every student with 1 entry for the deny table and none in the force table is placed here
leftovers = {}--Every student that doesn't have any entries in the force nor deny tables is placed here
unsortable = {}--None are placed here yet -- this is to store students that are unable to be placed according to set rules(i.e. a student being forced to be paired with someone in a group that also contains a student that they can't be paired with

SortStudentsIntoGroups()--predefined; sorts students into above groups
Run Code Online (Sandbox Code Playgroud)

在每个学生都被安排在这些小组之后(注意他们也仍留在学生桌上),我首先插入被迫在小组中配对的学生(好吧,我已经尝试过),插入有一个学生的学生或者将deny表中的更多条目放入可以放置它们的组中,然后用剩余的组填充剩余的组.

有几件事情会有所帮助:

numGroups--predefined number of groups
maxGroupSize--automatically calculated; quick reference to largest amount of students allowed in a group
groups = {}--number of entries is equivalent to numGroups(i.e. groups = {{},{},{}} in the case of three groups). This is for storing students in so that the groups may be displayed to the end user after the algorithm is complete.

sortGroups()--predefined function that sorts the groups from smallest to largest; will sort largest to smallest if supplied a true boolean as a parameter)
Run Code Online (Sandbox Code Playgroud)

正如我之前所说,我不知道如何为此设置递归算法.每当我尝试将强迫学生插入到一起时,我最终会将同一个学生分成多个组,强制对没有配对,等等.还要注意格式.在每个学生的强制/拒绝表中,给出了目标学生的姓名 - 而不是直接参考学生.我应该使用什么样的算法(如果这种情况存在的话)?任何帮助是极大的赞赏.

ami*_*mit 3

在我看来,你在这里面临着一个NP 难问题。

这相当于颜色的图形着色问题k,其中边缘是拒绝列表。

图表着色:

Given a graph G=(V,E), and an integer `k`, create coloring function f:V->{1,2,..,k} such that:
f(v) = f(u) -> (v,u) is NOT in E
Run Code Online (Sandbox Code Playgroud)

从图形着色到您的问题的 简化
:给定一个图形着色问题,(G,k)其中G=(V,E),使用以下命令创建问题的实例:

students = V
for each student: student.denial = { student' | for each edge (student,student')}
#groups = k
Run Code Online (Sandbox Code Playgroud)

直观上,每个顶点都由一个学生代表,并且学生否认所有学生在代表他们的顶点之间存在边。组数是给定的颜色数。

现在,给出您问题的解决方案 - 我们得到的k组如果学生u拒绝学生v- 他们不在同一组中,但这与着色相同u并且v颜色不同,因此对于原始中的每个边 (u,v)图表,u并且v有不同的颜色。
反过来也是类似的

因此,我们从图着色问题中得到了多项式约简,因此找到问题的最佳解决方案是 NP-Hard,并且该问题没有已知的有效解决方案,而且大多数人认为不存在。

一些替代方法是使用启发式方法,例如不能提供最佳解决方案的遗传算法,或使用耗时的强力方法(这对于大量学生来说是不可行的)。
蛮力只会生成所有可能的分组k,并检查它是否是可行的解决方案,最后 - 将选择找到的最佳解决方案。