-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMatcher.js
354 lines (324 loc) · 12.9 KB
/
Matcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*globals Logger, Workshop, Student */
/**
* Matcher Class.
*
* An object used to simulate a complete set of students and workshops, used to create the matches for each student with workshops.
*/
class Matcher {
constructor() {
// The number of sessions that an individual workshop has
this.sessionsPerWorkshop = 3; // maybe could be moved to a subclass
// An object containing all the workshops that can be indexed by workshop number
this.workshopsByNumber = {};
// An array containing Student objects representing every student
this.allStudents = [];
// An array containing Student objects that are preassigned
this.preAssignedStudents = [];
// An array containing all workshop objects sorted from least to most popular
this.workshopsByPopularity = [];
// An array containing all the workshops that aren't popular enough to be filled by people that list them as preferences
this.unpopularWorkshops = [];
// A number representing the quality of the final matches. The lower the score the better
this.score = 0;
// The minimum percentage that each workshop must be filled to
this.minimumWorkshopFill = 0.7;
// The number of preferences each student should have
this.numberOfPreferences = 6;
}
/**
* Adds a new Workshop into workshopsByNumber and workshopsByPopularity
*
* @param {string} name The name of the workshop.
* @param {int} number The number of the workshop.
* @param {int} capacity The capacity of each session of the workshop.
*/
addNewWorkshop(name, number, capacity, location) {
const thisWorkshop = new Workshop(
name,
number,
capacity,
location,
this.sessionsPerWorkshop,
this.minimumWorkshopFill
);
this.workshopsByNumber[number] = thisWorkshop;
this.workshopsByPopularity.push(thisWorkshop);
}
/**
* Adds a new Student object into allStudents
*
* @param {string} firstName The first name of the student.
* @param {string} lastName The last name of the student.
* @param {array} preferenceNums The student's preferences as an array of integers.
*/
addNewStudent(firstName, lastName, preferenceNums, grade) {
const preferenceArray = [];
for (const n in preferenceNums) {
const preference = this.workshopsByNumber[preferenceNums[n]];
preferenceArray.push(preference);
}
const student = new Student(
firstName,
lastName,
preferenceArray,
grade,
this.sessionsPerWorkshop
);
this.allStudents.push(student);
student.updatePopularities();
}
/**
* Adds a preassigned Student object into preAssignedStudents
*
* @param {string} firstName The first name of the student.
* @param {string} lastName The last name of the student.
* @param {string} grade The last name of the student.
* @param {array} assignments The student's assignments as an array of integers.
*/
addPreassignedStudent(firstName, lastName, grade, assignments) {
const student = new Student(
firstName,
lastName,
assignments,
grade,
this.sessionsPerWorkshop
);
for (let i = 0; i < assignments.length; i++) {
//for all assignments
const workshop = this.workshopsByNumber[assignments[i]];
student.assignWorkshop(workshop);
}
this.preAssignedStudents.push(student);
}
/**
* Helper function for sorting that compares two workshops by their popularity.
*
* @param {Workshop} workshopA A workshop to have its popularity compared to workshopB.
* @param {Workshop} workshopB A workshop to have its popularity compared to workshopA.
*/
morePopular(workshopA, workshopB) {
if (workshopA.popularityScore < workshopB.popularityScore) {
return -1;
} else if (workshopA.popularityScore > workshopB.popularityScore) {
return 1;
} else {
return 0;
}
}
/**
* Sorts the workshopsByPopularity array from least to most popular.
*/
sortWorkshops() {
this.workshopsByPopularity.sort(this.morePopular);
}
/**
* Appends "null" to a student's preference list if they have fewer than the correct number of preferences
*/
fixStudentPreferences() {
for (const student of this.allStudents) {
while (!student.hasAllPreferences()) {
student.preferences.push(null);
}
}
}
/**
* Calculates the absolute maximum percentage that every workshop can be filled to. this.minimumWorkshopFill can NOT be above this number.
*/
calculateMinPercent() {
let totalSlots = 0;
for (const workshop of this.workshopsByPopularity) {
totalSlots += workshop.totalBaseCapacity;
}
const minPercent =
(this.allStudents.length * this.sessionsPerWorkshop) / totalSlots;
Logger.log("minimum possible average fill: " + minPercent);
}
/**
* Hard copies an array and shuffles its contents randomly
*
* @param {array} array The array that will be hard copied and shuffled
*/
shuffle(array) {
const tempArray = array.slice();
const returnArray = [];
while (tempArray.length) {
const randomIndex = Math.floor(Math.random() * tempArray.length);
returnArray.push(tempArray[randomIndex]);
tempArray.splice(randomIndex, 1);
}
return returnArray;
}
/**
* Returns an array of students who are eligible to be assigned the given workshop as a filler workshop
*
* @param {Workshop} workshop A workshop that needs to be assigned as filler to some students
*/
findEligible(workshop) {
const eligibleStudents = [];
for (const student of this.allStudents) {
if (student.numberAssigned() < 2 && !student.isAssigned(workshop)) {
eligibleStudents.push(student);
}
}
return eligibleStudents;
}
/**
* Chooses random students to fill a workshop that hasn't been filled and gives them their highest possible preferences as compensation
*
* @param workshop the workshop that needs to be filled to Quorum
*/
fillOneWorkshop(workshop) {
const eligibleStudents = this.findEligible(workshop);
/*
* This portion of the function iterates through preferences 1 through 6 and assigns random students who have that preference
* open to the workshop until it reaches its quorum. If the preference for that student is full, then they are temporarily
* removed from the list of "eligible" students until the next preference iteration.
*/
for (let i = 0; i < this.numberOfPreferences; i++) {
// for each preference, starting with the highest
const currentStage = eligibleStudents.slice();
while (currentStage.length > 0) {
const randomIndex = Math.floor(
Math.random() * currentStage.length
);
const randomStudent = currentStage[randomIndex];
const preference = randomStudent.preferences[i];
if (preference === null) {
currentStage.splice(randomIndex, 1);
continue;
}
if (randomStudent.isAssigned(preference)) {
randomStudent.assignWorkshop(workshop);
} else if (!preference.isFull()) {
randomStudent.assignWorkshop(workshop);
randomStudent.assignWorkshop(preference);
}
currentStage.splice(randomIndex, 1);
if (workshop.hasReachedQuorum()) {
return;
}
}
}
Logger.log("Unable to fill workshop " + workshop.name);
Logger.log(
"Slots filled: " + workshop.slotsFilled + "/" + workshop.minimumFill
);
Logger.log("Base Popularity: " + workshop.popularityScore);
throw new Error("Was unable to fill workshop " + workshop.name); // will handle this differently if it happens, EXTREMELY unlikely
}
fillWithPreferred(workshop) {
for (let i = 0; i < this.numberOfPreferences; i++) {
// for each preference rank i
for (const student of this.allStudents) {
// for each student j
if (student.isAssigned(workshop) || student.fullyAssigned()) {
continue;
} else if (student.preferences[i] === workshop) {
student.assignWorkshop(workshop);
if (workshop.hasReachedQuorum()) {
return;
}
}
}
}
}
/**
* The main matching algorithm, fills every workshop to its minimum with the students who prefer that workshop the most
*/
reachMinimumForAll() {
/*
* Iterates through the workshops from least to most popular, filling each one with students who have it listed as their first
* preference, then those who have it listed as the second, etc. If the workshop is not filled by the time the end of all the
* preferences is reached, then the fillOneWorkshop() function is called to fill the remaining slots of the workshop until it
* reaches its minimum viable fill.
*/
for (let i = 0; i < this.workshopsByPopularity.length; i++) {
// for each workshop i
const currentWorkshop = this.workshopsByPopularity[i];
if (currentWorkshop.hasReachedQuorum()) {
continue;
}
this.fillWithPreferred(currentWorkshop);
if (!currentWorkshop.hasReachedQuorum()) {
this.fillOneWorkshop(currentWorkshop);
}
}
}
/**
* The final portion of the matching algorithm, gives the students their highest possible preferences who are not already assigned to max workshops
*/
finalMatches() {
for (const student of this.allStudents) {
// for every student i
if (!student.fullyAssigned()) {
// if the student still has empty slots
for (const preference of student.preferences) {
// for each student preference j
if (preference === null) {
continue;
} else if (student.canBeAssigned(preference)) {
student.assignWorkshop(preference);
if (student.fullyAssigned()) {
break;
}
}
}
}
if (!student.fullyAssigned()) {
const shuffledWorkshops = this.shuffle(
this.workshopsByPopularity.slice()
);
for (let i = 0; i < shuffledWorkshops.length; i++) {
const randomWorkshop = shuffledWorkshops[i];
if (student.canBeAssigned(randomWorkshop)) {
student.assignWorkshop(randomWorkshop);
if (student.fullyAssigned()) {
break;
}
}
}
}
}
}
/**
* Assigns every student to workshops according to their preferences.
*/
matchGirls() {
this.sortWorkshops();
this.fixStudentPreferences();
this.reachMinimumForAll();
this.finalMatches();
}
/**
* Give a score to the final matches based on how many students received their preferences.
*/
scorer() {
this.score = 0;
for (const student of this.allStudents) {
// For each student i
this.score += student.calculateScore();
}
}
/**
* Logs the names of all students who received none of their preferred workshops.
*/
checkMatches() {
let numberOfFails = 0;
for (const student of this.allStudents) {
// For each student i
const worstScore = this.unpreferredScore * this.sessionPerWorkshop;
if (student.compareToScore(worstScore)) {
numberOfFails += 1;
}
}
if (numberOfFails > 0) {
Logger.log(
"There was a matching failure, " +
numberOfFails.toString() +
" students did not get any of their preferences"
);
} else {
Logger.log("Every student got at least one preference");
}
}
}