C++ Program to find joining year from the course year lists


Suppose we have an array A with n elements. In a university for each course there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x years from the year of university entrance of this student. The value of x is not given, but it can be determined from the available data. A is a list of groups which the student Amal joined. According to this information we have to find the year of Amal's university entrance.

Problem Category

This problem falls under sorting problems. Sorting is a very common problem while we are talking about different problem solving algorithms in computer science. As the name suggests, sorting indicates arranging a set of data into some fashion. We can arrange them in nondecreasing order or non-increasing order in general. Otherwise sorting can be also takes place in a pre-defined manner. For the string based problems, sometimes we refer lexicographical sorting to arrange letters in dictionary fashion. There are plenty of different sorting techniques with certain variations and their time and space complexity. To date, the lower-bound of the time complexity for comparison based sorting techniques is O(n*log n). However there are some mechanical sorting techniques like bucket sort, radix sort, counting sorts are there whose time complexity is linear O(n) in time. For further reading, please follow the link below −

https://www.tutorialspoint.com/data_structures_algorithms/sorting_algorithms.htm

So, if the input of our problem is like A = [2014, 2016, 2015], then the output will be 2015.

Steps

To solve this, we will follow these steps −

b := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   b := b + A[i]
return b / n

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int b = 0;
   int n = A.size();
   for (int i = 0; i < n; i++){
      b += A[i];
   }
   return b / n;
}
int main(){
   vector<int> A = { 2014, 2016, 2015 };
   cout << solve(A) << endl;
}

Input

{ 2014, 2016, 2015 }

Output

2015

Updated on: 07-Apr-2022

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements