There’s a problem I have trouble solving.
Shortly written, here’s how it goes:
There are N professors at a school, born in a certain year and you need to find the amount of years the professors share (if two professors share a year, it’s one year which is repeated).
Example: Input: (first line) 3 (second line) 1975 1960 1975 Output: (third line) 1
I’ve started somehow, and I have only managed to create the input:
int N;
cin >> N;
int array[N];
for (int i = 0; i < N; i++) {
cin >> array[i];
}
Now, I don’t know how to continue, or use the information (years) the user has entered.
Edit: Although there might be better ways of solving this, I am just looking for a simple solution, or a code explaining how I can continue this program.
Edit: It should display the amount of years which repeat.
In your program above, you were able to have the user input how many years they are entering as well as the years you are comparing. Now to get the output, you should use for loops to iterate through the array and compare the years.
For example:
User entered: 1975 1960 1975
In your code this will be stored as: array[0] = 1975, array[1] = 1960, array[2] = 1975.
One option I would suggest would be:
Iterate through the array and count the number of duplicates. If we find a higher count, then set that as the highest number of duplicates.
Example: Read in 1975 and compare with each element if there are duplicates. If we find a duplicate, then increase the counter. If the counter is greater than the highest count, then that becomes the highest count. Repeat this process for the entire array.
Program:
int N;
cin >> N;
int A[N];
int highest_count = 0;
for (int i = 0; i < N; i++) {
cin >> A[i];
}
for (int i = 0; i < N; i++) {
int counter = 0;
for (int j = i; j < N; j++) {
if (A[i] == A[j] {
counter++;
}
if (counter > highest_count) {
highest_count = counter;
}
}
}
cout << highest_count;
Related
I have two solutions for this problem, but which is one is optimal?
A list of N numbers is given. The player has to arrange the numbers so that all the odd numbers of the list come after the even numbers. Write an algorithm to arrange the given list such that all the odd numbers of the list come after the even numbers.
Input
The first line of the input consists of an integer numbers, representing the size of the list(N).
The second line of the input consists of N space-separated integers representing the values of the list
Output
Print N space-separated integers such that all the odd numbers of the list come after the even numbers
Example
Sample Input
8
10 98 3 33 12 22 21 11
Sample Output
10 98 12 22 3 33 21 11
Solution no1-
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
int p1=0, p2= n-1;
while(p1 < p2){
while(a[p1]%2 == 0 and p1<p2)
p1++;
while(a[p2]%2 != 0 and p1<p2)
p2--;
if(p1 < p2){
swap(a[p1], a[p2]);
p1++;
p2--;
}
}
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
return 0;
}
solution 2-
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]%2==0)
cout<<arr[i]<<" ";
}
for(int i=0;i<n;i++){
if(arr[i]%2!=0)
cout<<arr[i]<<" ";
}
return 0;
}
I would make a few changes, but mostly follow the second example.
First, I would put in an if-statement to ensure that n is a positive number. That's just a good check to do.
Next, I wouldn't output them quite like this. I'd build a second array instead.
int inputArray[n];
int finalArray[n];
int outputIndex = 0;
... Fill inputArray like you currently fill array
for (int i = 0; i < n; ++i) {
if (inputArray[i] % 2 == 0) {
outputArray[outputIndex++] = inputArray[i];
}
}
Do the second loop the same way. Then dump the outputArray.
Now, some other notes. These are stylistic, but will help you. Please use more whitespace in your code. Notice my code has spaces between operators. You're clearly young with young eyes, but good habits now will matter when you have to share code with old farts. Your scrunched-together code is really quite difficult to read and can readily hide errors. You wouldn't believe how many bugs are in code because some programmer was afraid of spaces.
Second, many programmers will tell you that optional braces shouldn't be treated as optional. Notice my if-statement has a pair of braces whereas yours don't. And if you look at how your code was formatted, you'll see that your indentation is wrong. You didn't indent your cout lines properly. This is a way errors hide. If you always use braces, evne when the language thinks they're optional, you'll have fewer bugs.
Lastly, most people will suggest you stop using fixed-length arrays and instead use vector, but as you're a new programmer, maybe you're not ready for that.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int* arr = new int[n];
int* odd = new int[n];
int* even = new int[n];
int oddIndex = 0;
int evenIndex = 0;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]%2==0)
even[evenIndex++] = arr[i];
else
odd[oddIndex++] = arr[i];
}
for(int i=0;i<evenIndex;i++){
cout<<even[i]<<" ";
}
for(int i=0;i<oddIndex;i++){
cout<<odd[i]<<" ";
}
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I was solving this problem in Hackerrank.
This question will give us an array of scores. We have to rank those sores as per the dense leader board ranking. It means the highest score gets the first rank, if the next score is equal to the highest rank, we give them the same rank. If it is less than that, we give it the next immediate rank.
ex- the scores 100, 80, 80, 60 will get ranks 1, 2,2 3.
ALso we are given an array of alice's score and we have to find out what rank Alice will get with each of her score.
Note that the scores are given in descending order. And Alice's scores are given in ascending order.
WHat I do is first create an array whoose ith element will denote the rank of ith score in the score vector.
Then I take the smallest score of ALice and do a search of the smallest score >= Alice's score. Then I gave ALice's score the rank accordingly. AFter that I pick the second smallest alice score and this time start searching for the smallest score >= Alice's score from where I left off.
This is the code that I wrote-
#include <vector>
#include <iostream>
using namespace std;
//function for the question.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice)
{
vector<int> rank; //another array that will store the rank of all people already on the leaderboard
vector<int> result; //vector that will store the return value of alice's rank.
int val = scores[0]; //stores the current score that we are pointing on.
int len = 1, k, n = 0; //len is the current rank we are on. it changes if value(score) changes.
for (int i = 0; i < scores.size(); i++) {
if (scores[i] == val) { //if the scores are equal...
rank.push_back(len); //it stores the value of len that is the rank. This command ensures that the same scores have the same rank.
}
else if (scores[i] < val) { //if the score is less than val....
len++; //increments len by 1.
rank.push_back(len); //gives the current len as rank to the next person.
val = scores[i]; //sets the new value to the current score
}
}
//now I have stored ranks. Now for giving alice ranks...
k = scores.size() - 1; //points to the current score that we are comparing for Alice.
for (int j = 0; j < alice.size(); j++) { //does the loop for every score of Alice given.
k = n; //sets k=n so that we begin our search with the same index we left on for the next time.
while (k >= 0) {
if (scores[k] < alice[j]) { //if score is less, sub 1 from k
k--;
}
else if (scores[k] == alice[j]) {
result[j] = rank[k]; //if scores are equal, we set the rank of alice same as that of the rank that this score got.
n = k; //we store the value of k for which the scores are equal.
k = -1; //to end the while loop
}
else if (scores[k] > alice[j]) {
result[j] = rank[k] - 1;
n = k; //we do the same if the scores are one less, but give one less rank
k = -1;
}
}
}
return result; //return the vector.
}
// main function just takes in all the values and prints the vector that we get
int main()
{
int n, value, m;
cin >> n;
vector<int> scores;
vector<int> alice;
for (int i = 0; i < n; i++) {
cin >> value;
scores.push_back(value);
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> value;
alice.push_back(value);
}
vector<int> result;
result = climbingLeaderboard(scores, alice);
for (int k = 0; k < m; k++) {
cout << result[k];
cout << endl;
}
return 0;
}
It is showing a runtime error. Pls look at the code and tell me whats wrong. Also I would suggest to look at the link once bcoz it will explain the question much better than I evr will.
It also contains the sample inputs and sample outputs. The input format is a bit strange.
Looking at the debug output it's clear that you have an out of bounds access on one of your vectors.
Looking at the code I can see at least one such problem (there may be more)
vector<int> result;
...
result[j]=rank[k];
...
result[j]=rank[k]-1;
result is a vector with size 0, at no point do you resize it. So result[j]=... is an out of bounds vector access.
I will start by saying that I'm not a native speaker so please excuse me my grammatical errors.
I'm an university student and my task is the following: I have an input that tells me the number of people, and then every line contains the time of arrival and the time of exit, both natural numbers separated by a space.
I have to find the (index of the) person who met the most people and then output the number of meetings that person had.
Example input and output:
If person A has datestamps of 3 and 6 and person B has 6 and 7, it is still considered a meeting.
I already solved this problem with a fixed size array of structs that compares every person to everybody else to find out the number of meetings and then searched for the person with the most meetings.
My problem is that this code is very slow and I must hadle inputs consisting of maximum 200000 people and timestamps ranging from 1 to 1000000.
This - compare everyone with everyone else - solution works for small sample sizes, but there is no way it can work for 200000 structs.
Also, this code has to successfully run under 0.2 sec.
What is a faster way to solve this?
#include <iostream>
using namespace std;
const int maxN = 20000;
struct Data {
int arrival;
int departure;
int meetings = -1;
};
int main()
{
Data x[maxN];
int N;
///input
cin >> N;
for (int i = 0; i < N; i++) {
cin >> x[i].arrival;
cin >> x[i].departure;
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++){
if ( ((x[i].arrival >= x[j].arrival && x[i].arrival <= x[j].departure) || (x[i].departure >= x[j].arrival && x[i].departure <= x[j].departure)) || ((x[j].arrival >= x[i].arrival && x[j].arrival <= x[i].departure) || (x[j].departure >= x[i].arrival && x[j].departure <= x[i].departure)) ) {
x[i].meetings++;
}
}
}
int maxInd = 0;
int maximum = 0;
for(int i = 0; i < N; i++) {
if (x[i].meetings > maximum){
maxInd = i;
maximum = x[i].meetings;
}
}
///output
cout << maxInd+1 << endl;
cout << maximum << endl;
return 0;
}
I will only give you a starting point...
If I had to solve it, i would start by defining the following structure:
struct come_or_go {
size_t person_index;
int time;
bool arrival; // true for arrival, false for leaving
};
Next I would read the input into a vector<come_or_go> with two entries for each person. One when it arrives and one when it leaves. Next I'd sort that vector with respect to the elements time member. Finally I'd try to come up with a clever idea that requires to traverse this vector only once.
So far thats all I can provide, maybe I will update when I can give more hints. Hope this helps to push you into a differernt direction, because your brute force simply looses by complexity. Instead of trying to get details of it "faster" you need to change your overall approach.
I managed to do it by creating a vector and storing the 100.000 points of time in it.
I added 1 to each index where a person came in, stayed, and left.
Working with 100.000 long vectors, I managed to solve this problem with only one for loop se it ran reasonably fast.
Paradox with averages Programming problem
I have an class of Computer Science students represented with an array, and a class of Economics students also represented as an array.
The array is filled with values representing each students IQ.
One well-known joke goes as follows: If a bad Computer Science student drops out of college and goes to a different college to study Economics instead, he will increase the average intelligence on both colleges.
I have to run through the computer science array and check if each student leaves and joins economics, will he increase the average IQ of both groups. I then have to count how many students and print to the screen.
I seem to have gotten the right answer but one of the test cases is wrong, can anyone lay their wisdom upon me? thanks.
int main() {
int cases;
cin >> cases;
for(int i = 0; i < cases; i++)
{
int numCs;
int numEc;
cin >> numCs;
cin >> numEc;
int csArray[numCs];
int ecArray[numEc];
long csTotal = 0;
long ecTotal = 0;
for(int j = 0; j < numCs; j++)
{
cin >> csArray[j];
csTotal += csArray[j];
}
for(int j = 0; j < numCs; j++)
{
cin >> ecArray[j];
ecTotal += ecArray[j];
}
double csAvg = csTotal / (double)numCs;
double ecAvg = ecTotal / (double)numEc;
int count = 0;
for(int j = 0; j < numCs; j++)
{
if((csArray[j] < csAvg) && (csArray[j] > ecAvg))
{
count++;
}
}
cout << count << endl;
}
return 0;
}
You second loop should run till numE not numC.
Also floating point division can be tricky at times since it is a finite approximation so line
if((csArray[j] < csAvg) && (csArray[j] > ecAvg))
can be replaced by
(csTotal > numCs * csArray[j]) && (ecTotal < numEc * csArray[j])
This conveys the same meaning without the hassle of floating point computation.
I'm having trouble finding the second smallest integer in my array. The array is unsorted (it's what's in the data.txt file), so I know that might be part of the problem, I'm not sure how to fix this in the simplest way. Afterwards I have to remove that integer from the array, move every number over and reprint the array, if anyone could help I'd really appreciate it.
const NUM = 10;
int Array[NUM];
ifstream infile;
infile.open("Data.txt");
for (int i = 0; i < NUM; i++)
{
infile >> Array[i];
cout << Array[i] << endl;
}
int Min = Array[0];
int Next = 0, SecondMin = 0;
for (int k = 0; k < NUM; k++)
{
if (Min > Array[k])
Min = Array[k];
}
for (int m = 2; m < NUM; m++)
{
Next = Array[m];
if (Next > Min)
{
SecondMin = Min;
Min = Next;
}
else if (Next < SecondMin)
{
SecondMin = Next;
}
}
cout << "The second smallest integer is: " << SecondMin << endl;
You don't have to loop over the array twice to find the second smallest number. As long as you're keeping track of both the smallest and the second smallest, you should be able to find them both with a single loop.
There are a couple of other problems with this code:
Your check for end of file should probably be if (!infile.eof())
You don't need to check if (i < NUM) inside your loop. i will always be less than NUM due to the constraint on the loop.
If for some reason the number of items in the file is less than NUM, the rest of the items in the array will have undefined values. For instance, if there were only nine items in the file, after reading the file, Array[9] would have whatever value happened to be in that spot in memory when the array was created. This could cause problems with your algorithm.
I assume that this is some sort of homework problem, which is why the use of an array is required. But keep in mind for the future that you'd probably want to use a std::vector in this sort of situation. That way you could just keep reading numbers from the file and adding them to the vector until you reached the end, rather than having a fixed number of inputs, and all of the values in the vector would be valid.