我是一所独立寄宿学校的老师,我正在尝试用C++编写一个程序,该程序会随机将学生安排在餐厅的餐桌旁,这样他们每周都会与不同的学生和不同的工作人员坐在一起.理想情况下,在一定时期内,他们不会两次坐在同一张桌子上,并且尽可能多的不同学生.我用Python创建了这个程序,它运行得很好(非常好).出于各种原因,我试图将其移植到C++(我根本不熟悉),所以我可以把它交给寄宿人员.学生和教职员工(以及表格容量)都是从文本文件中读取的.我创建了两个自定义类,一个用于学生,一个用于表,用于处理数据.以下是两个类头文件:
Table.h
#pragma once
#include <iostream>
#include "Student.h"
#include <vector>
using namespace std;
class Table
{
// Private class variables
string staff;
int numSeats;
vector<Student> seating;
public:
Table(); // Default constructor
Table(string s, int n);
Table(const Table& that) : staff(that.staff), numSeats(that.numSeats)
{
}
// Copy Constructor
Table& operator=(const Table& that)
{
staff = that.staff;
numSeats = that.numSeats;
return *this;
}
int getNumSeats();
string getStaffName();
void addStudent(Student student);
void removeStudent(Student student);
void clearStudents();
vector<Student> getTableSeating();
int getRemainingSeats();
~Table(void);
};
Run Code Online (Sandbox Code Playgroud)
这是学生班级文件:
#pragma once
#include <iostream>
#include <vector>
using namespace std;
class Student
{
string name;
string country;
vector<int> tablesSatAt;
public:
Student(string n, string c);
Student();
Student(const Student& that) : name(that.name), country(that.country)
{
}
Student& operator=(const Student& that)
{
name = that.name;
country = that.country;
return *this;
}
string getName();
string getCountry();
void addTable(int tableNumber);
void removeTable(int tableNumber);
bool satAtTable(int tableNumber);
friend bool operator==(Student s1, Student s2);
friend bool operator!=(Student s1, Student s2);
~Student(void);
};
bool operator==(Student s1, Student s2);
bool operator!=(Student s1, Student s2);
Run Code Online (Sandbox Code Playgroud)
这是执行繁重工作的递归函数:
bool seatRecursive(vector<Student> &tempStudents, vector<Table> &tempTables)
{
if (tempStudents.size() == 0) return true; //base case
Student nextStudent = randomSelect(tempStudents);
for (vector<int>::size_type i=0; i<tempTables.size(); i++)
{
if (tempTables[i].getRemainingSeats() > 0 && !nextStudent.satAtTable(i))
{
addStudentToTable(nextStudent, tempTables, i);
if (seatRecursive(tempStudents, tempTables)) return true;
else
{
removeStudentFromTable(nextStudent, tempTables, i);
tempStudents.push_back(nextStudent);
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
大部分都有效.当我运行该程序时,我得到一个有10周座位的文本文件,但所有桌面座位都是相同的.即如果我是一名特定的工作人员,我有同样的孩子在我的餐桌上待了整整10个星期.我有一个int的向量,应该存储学生随时间坐着的表号.在调试时,我注意到那些表号不存储在该向量中,它总是空的.我的问题是,我无法弄清楚为什么会这样.是因为我通过引用传递向量吗?是否与指针有关,即使我没有明确声明指针?
非常感谢任何建议,如有必要,我可以粘贴其余的代码.
布赖恩
为什么这么难?
只需将所有学生放在一个向量中,然后使用STL random_shuffle算法,最后将生成的学生矢量线性地放在所有可用的表中.
你甚至不需要为学生或桌子定制课程
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |