我有一个大学项目,我必须逐级打印不同班级学生之间的关系。这个想法是,如果我们有约翰和克里斯在同一班上学习,他们是第一级的朋友,如果克里斯在同一班上学习数学,那么约翰和数学是第二级的朋友。我研究这个问题,我发现算法,如this,但我的主要问题是,我使用对象作为输入数据:会员之间的打印关系
<?php
class Student {
private $id = null;
private $classes = [];
public function __construct($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function getClasses() {
return $this->classes;
}
public function addClass(UClass $class) {
array_push($this->classes, $class);
}
}
class UClass {
private $id = null;
private $students= [];
public function __construct($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function getStudents() {
return $this->students;
}
public function addStudent(Student $student) {
array_push($this->students, $student);
$student->addClass($this);
}
}
function getRelations(Student $start_student, &$tree = array(), $level = 2, &$visited) {
foreach ($start_student>Classes() as $class) {
foreach ($class->Students() as $student) {
if($start_student->getId() != $student->getId() && !is_int(array_search($student->getId(), $visited))) {
$tree[$level][] = $student->getId();
array_push($visited, $student->getId());
getRelations($student, $tree, $level+1, $visited);
}
}
}
}
$class = new UClass(1);
$class2 = new UClass(2);
$class3 = new UClass(3);
$student = new Student(1);
$student2 = new Student(2);
$student3 = new Student(3);
$student4 = new Student(4);
$student5 = new Student(5);
$student6 = new Student(6);
$class->addStudent($student);
$class->addStudent($student2);
$class->addStudent($student4);
$class2->addStudentr($student2);
$class2->addStudent($student4);
$class2->addStudent($student5);
$class3->addStudent($student4);
$class3->addStudent($student5);
$class3->addStudent($student6);
$tree[1][] = $student->getId();
$visited = array($student->getId());
getRelations($student, $tree, 2, $visited);
print_r($tree);
我被困在写作getRelations()应该创建一个数组,它是类似功能
Array ([1] => Array ([0] => 1) [2] => Array ([0] => 2 [1] => 4) [3] => Array ([0] => 5 [1] => 6))
但我无法获得递归权(或可能是整个算法)。任何帮助将不胜感激。
是的,我的第一个想法是完全错误的,我在这里错过了一些代码,但你可以在下面检查我自己的答案,并给出你的意见。 – Lexx
对我来说似乎还可以(但我需要再次强调我对PHP不熟悉)。不过,我确实有几个问题:a)我不太明白为什么你的PrintStudent方法有一个参数$ lvl; b)在我看来,$ lvl的初始值应该是零,但是代码表明它是1.因此(c)你有多少个测试用例运行并检查,并且是否有失败? –
$ lvl是一个可选参数,它可以是0或1,它只是从我解决问题的尝试中留下的。我尝试了不同的场景,到目前为止它没有错误地打印学生,没有重印已经打印的连接。它也起作用,因此它只显示最短的连接。 – Lexx