To put it simply, I have a small program with these structs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
struct Student
{
int id;
string name;
};
struct Course
{
int id;
string name;
};
struct Grade
{
int studentId;
int courseId;
bool passed;
};
|
I have an array of Students (let's call it studentsArray), an array of Courses (coursesArray) and an array of Grades (gradesArray) to store collections of each one of the structs.
Grades will tell if a specific student passed a specific course or not in any given year. BUT there can be students who took no courses at all that year. That is, not all of the students in the studentsArray will be linked to an element in the gradesArray.
So I thought of two different options to do this:
First option:
a) I use a bubble sorting algorithm to sort the gradesArray so all studentId are grouped. Then I proceed like this:
b) read the first studentId in the sorted gradesArray and store it in a temporary variable. I also start a counter at 1.
c) I keep iterating through the gradesArray while the studentId in the current element is the same as in the temp variable, incrementing the counter.
d) When it changes I know I won't find any other elements linking that student so I can show the counter.
e) Assign the newly found studentId to the temp variable and restart the counter.
Second option:
This uses a nested iteration.
a) I iterate through the studentsArray.
b) For each student id, I start a counter in 0 and iterate through the whole gradesArray to see if that student id is linked to any Grade element.
c) If it is, I increment the counter.
d) When I finish iterating through the whole gradesArray, I print the counter if it's greater than 0.
e) Then I move to the next studentsArray item and go back from b).
Is the second option absolutely inefficient and a no-no? Or both are valid considering this is a beginner exercise? I mean, despite being a beginner exercise, I still want to follow good programming practices.