我有三个变量
Group-Set of Persons 例如:{{David, Sebastian, Yousef}, {Boris, Mark}}
人物集 例如:{David, Mark, Sebastian, Boris, Yousef}
关系集 例如:{{David, Mark}, {Sebastian, Boris}}
Group-Set 不能有任何人彼此是 friend 。
组集不能有重复项。
我需要创建一个名为的 divide 方法
divide(person-set, relation-set) 并返回一个组集,如上例所示。
需要递归求解,不允许循环
我已经有一个名为 areFriends(Person, Person) 的方法,如果他们是 friend ,它会返回一个 bool 值。
这是我到目前为止得到的:
divide(ps, r){
divide(ps, r, gs){
let p1 = getRandom(ps);
p2 = getRandom(ps);
if(areFriends(p1, p2) = false){
gs.add(p1);
gs.add(p2);
}
remove(p1, ps);
if(getRandom(ps) != 0){
divide(ps, r, gs);
}
}
我已经处理这个问题很长时间了,真的需要帮助。谢谢!
最佳答案
基于一个新的约束(没有循环约束),我们需要一个指标(g_ind
)来考虑函数中的组:
divide(ps, r, g = [[]], g_ind = 0)
p <- empty
if there is any person in ps:
p <- take the first person from ps
else:
return
if g_ind >= len(g):
// all current divisions in g have a friend of p
g.add([p]) // add a new division with initial member p
remove p from ps
divide(ps, r, g, 0)
return
else if any friends of p in r exists in g[g_ind]:
divide(ps, r, g, ++g_ind)
return
else:
g[g_ind].add(p)
remove p from ps
divide(ps, r, g, 0)
return
关于algorithm - 解决递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64226790/