3
\$\begingroup\$

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; 
}
forsvarir
11.8k7 gold badges39 silver badges72 bronze badges
asked Feb 8, 2017 at 16:09
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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.

answered Feb 8, 2017 at 18:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.