I've written a short Random Exam Generator program. There are 6 days, 3 time slots per day. One day can not have more than 2 exams. There will be 5 exams in total.
I am fairly new to programming so I would like some feedback on how well this code is written, and if there are any ways to improve it.
var exam_days =
{ 0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0 };
var exam_array = [];
function generateSchedule() {
for (var i = 0; exam_array.length < 5; i++){
var time = getRandomInt(0,2);
var day = getRandomInt(0,5);
var exam_id = "exam-" + time + day;
if (dayAvailable(day, exam_days) && uniqueExam(exam_id, exam_array)) {
exam_days[day] += 1;
exam_array.push(exam_id);
document.getElementById(exam_id).style.background = "green";
}
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function dayAvailable(date, exam_days) {
if (exam_days[date] < 2) {
return true;
}
return false;
}
function uniqueExam(exam, exam_array)
{
var count = exam_array.length;
for (var i = 0; i < count; i++)
{
if (exam_array[i] === exam)
return false;
}
return true;
}
1 Answer 1
Library functions usage
The unique_exam
function is basically checking if the exam is in the array or not and returning false if it is not, the includes
method is what You need.
return ! exam_array
.includes
(exam)
Inline
dayAvailable
Should be inlined as it boils down to just one comparison, instead the number of exams per day should be saved as a constant.