Trying to find root mean square of two rows in array - c++

i am working through an EDX course on computer programming. I have come to this problem and dont know how to work through it. im not looking for an answer but more a point in the right direction.
so the question gives you a 2D array. two columns and N amount of rows. the N is the number of students. each column is the grade of first test and then the second is the grade of the second test. I am asked to find the root mean square of two seperate kids and compare them and then return a number based off the comparison. The question gives you this formula
RMS = (0.5×(midsem_marks2 + endsem_marks2))0.5
I know how to get the appropriate marks using array[index 1(firsttest)] etc and then how to compare them. However, i am clueless on how to write that formula. any help would be great. Thanks in advance.
code I have
float RMSi1 = sqrt(.5*((marksarray[index1][0]*marksarray[index1][0])+(marksarray[index1][1])*(marksarray[index1][1])));
float RMSi2 = sqrt(.5*((marksarray[index2][0]*marksarray[index2][0])+(marksarray[index2][1])*(marksarray[index2][1])));
if(RSMi1>RSMi2){
return -1;
}
if(RSMi1<RSMi2){
return 1;
}
if(RSMi1==RSMi2){
return 0;
}
I'm getting an error that the RSMi1 and 2 are not declared in the if statements
Input marksarray:
1 2
1 60 20
2 60 20
3 30 40
4 10 90
5 90 30
6 0 100
7 60 20

Related

Knapsack problem with multiple availabe packages using dynamic programming

Hello and thanks for helping!
So we've got a list of fireworks containing 1) Number in stock 2) Number of fireworks in this package 3) Diameter which equals the noise and
4) The price.
This is the list:
25 17 10 21
10 15 10 18
5 16 10 19
10 15 12 20
15 9 11 12
10 7 28 23
8 7 16 11
10 6 16 10
25 10 18 25
25 12 18 27
10 5 40 35
60 40 5 27
5 25 30 90
50 1 60 8
Our task is to create a shopping list and buy fireworks so we get the highest possible noise. We've got a knapsack capacity of 1000€. We're also supposed to solve this without using tables (so with dynamic programming instead).
I only use one class called Package which contains the four constraints as shown above.
At first I thought it would make sense to try to write an algorithm for a normal knapsack, so just with the price and the diameter (=weight). I tested it with a different list and it worked perfectly fine. I just iterated through all packages and then again used a nested for loop to find the best constellation (exhaustive search). My next idea was to merge the number of fireworks per package with the diameter, because fireworks can only be bought in a full package.
The only thing left which I still haven't found out is what to do with the amount of packages in stock. Like, with my current algorithm it just buys all packages of a firework until the knapsack is full. But obviously that won't be correct.
void knapsack(vector<Package*> stock){
vector<int> indices, tmp_indices;
int noise,tmp_noise= 0;
int price;
for (unsigned int i = 0; i < stock.size(); i++) {
price = stock[i]->price;
noise = stock[i]->diameter*stock[i]->number_fireworks;
indices.push_back(i);
for (unsigned int j = 0; j < stock.size(); j++) {
if (i != j) {
if (price+stock[j]->price<= BUDGET) {
price+=stock[j]->price;
noise+=stock[j]->diameter*stock[j]->number_fireworks;
indices.push_back(j);
}
}
}
// After second loop we have a new possible constellation
// Check if the previous constellation had a lower value and if so, set it to the current one
if (noise > tmp_noise) {
tmp_noise = noise;
tmp_indices.clear();
// tmp save
for (auto &index : indices) {
tmp_indices.push_back(index);
}
}
price= 0;
noise = 0;
indices.clear();
}
// Best constellation found, Print the shopping list
cout << "\Stock.\tNum\Diameter.\Price\n" << endl;
for(unsigned int i = 0; i < tmp_indices.size(); i++) {
cout << stock[tmp_indices[i]]->stock<< "\t";
cout << stock[tmp_indices[i]]->number_fireworks<< "\t";
cout << stock[tmp_indices[i]]->diameter<< "\t";
cout << stock[tmp_indices[i]]->price<< "\t\n";
}
}
We've been told that we should be able to spend exactly 1000€ to get the correct constellation of fireworks. My idea was to add another for loop to iterate through the amount of available packages, but that didn't really work...
This was our first lesson and I'm a bit desperate, because we have only learned how to solve a knapsack problem with 2 constraints and by using a table R.
Edit: Since one user insisted to get a specific question, here it is: Is the idea of using another loop to include the third constraint correct or is there a better/easier way of doing it? Or is it possible that I need a completely different approach for a knapsack with 3 instead of 2 constraints?
Thanks for help in advance

3n+1 uVa gives WA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My initial question was a bit vague, so here's the edited question.
The 3n+1 uVa problem is based on the Collatz Conjecture.
Consider any positive integer 'n'. If it is even, divide it by 2. If it is odd, multiply it by 3 and add 1. After 'x' such repeated operations, you will get 1. This has been proven for very large numbers by supercomputers.
UVa Online Judge is an online automated judge for programming problems hosted by University of Valladolid.
Here's a link to the problem statement:
uVa 3n+1
Please read the problem statement before looking at my code!
The uVa online judge runs your code against certain test-cases and tells you if your solution was right or wrong. It does not tell you why it failed (if your solution was wrong).
Here is the link again if you missed the first one:
The link to the problem description
I don't understand what I am missing out or skipping (since I am getting Wrong Answer) in my code logic. I have tried lots of test cases, and they seem to be working fine. I know the logic can be compressed to a large extent, but I just need to figure out where the flaw is for now.
Here is my code. I know bits/stdc++ shouldn't be used, but currently, it's not affecting my code. Please review it if you can and help me out.
#include<iostream>
#include<cstdlib>
#include<bits/stdc++.h>
using namespace std;
int main()
{
unsigned long int num;
int i,j,tempi, tempj,temp;
//Scanning until inputs don't stop
while(scanf("%d %d",&i,&j)!=EOF)
{
//Boolean variable to set if i is greater
bool iwasmore=false;
//Boolean variable for equal numbers
bool equalnums=false;
int cycles=1, maxcycles=0;
if(i>j)
{
//swapping for the for loop to follow
temp=i; i=j; j=temp;
iwasmore=true;
}
if(i==j)
{
equalnums=true;
}
tempi=i; tempj=j;
//Taking each number in the given range and running it in the algorithm.
//The maxcycles variable will have the value of the maximum number of cycles
//that one of the numbers in the range took (at the end of the for loop).
for(num=i;num<=j;num=(++tempi))
{
if(cycles>maxcycles)
{
maxcycles=cycles;
}
cycles=1;
//The actual algorithm
while(num!=1)
{
if(num%2==1)
{
num = (3*num)+1;
cycles++;
}
else
{
num=(num/2);
cycles++;
}
}
if(equalnums==true)
{
maxcycles=cycles;
equalnums=false;
}
//Resetting num
num=0;
}
if(!iwasmore)
cout<<i<<" "<<j<<" "<<maxcycles<<endl;
else
cout<<j<<" "<<i<<" "<<maxcycles<<endl;
}
return 0;
}
Here is the output I am getting for the following input:
Input:
1 1
10 1
210 201
113383 113383
999999 1
Output:
1 1 1
10 1 20
210 201 89
113383 113383 248
999999 1 525
Another testcase:
Input:
1 5
10 8
210 202
113383 113383
999999 999989
Output:
1 5 8
10 8 20
210 202 89
113383 113383 248
999999 999989 259
The cycle length of the last number checked is never compared against maximum.
For Input:
8 9
9 9
The program outputs
8 9 4
9 9 20
But the correct answer is
8 9 20
9 9 20
Put
if (cycles > maxcycles) {
maxcycles = cycles;
}
at the end of the for-loop, instead of at the beginning.

Need Help in a Project of C++

So this is the actual Problem
Can anyone tell me that how I read the repective Data from the file, and how would I able to store it in variables (without using array) also the code should be generic, That if the number of series will incresed or decresed.. Code will not be affected... I Just can't understand that how would I store sata in variables and how.. Please Help.. :(
Problem
A file contains information of a batsman. Information is no of series
played by the batsman. No of matches played in each series & score in
each match by the batsman. You have to read the data (without using
any array) and find average score and maximum score in all matches of
a series. In the end find overall average score and max score in all
matches.
Input:
Read data from file "cricket.txt". First line contains no of seasons/
series played by the player. Next pair of lines contains matches
played by the batsman followed in next line scores by batsman in
different matches of a season. See sample "cricket.txt"
5
6
93 75 41 40 90 19
5
45 86 30 60 29
3
47 90 33
4
22 2 92 5
5
88 67 96 91 90
First 5 shows player has played 5 seasons/ series
Next 6 show in first series player has played 6 matches
Next line has scores of player in 6 matches
Next 5 show in second series player has played 5 matches
Next line has scores of player in 5 matches
So on in second last line 5 shows player has played 5 matches in 5th
series
Last line has scores of player in 5 matches of last series
You're looking for an array.
int a[10];
// Loop that assigns all elements in array a to 0
for (int i = 0; i < 10; i++)
{
a[i] = 0;
}
// Array b will have all of it's members initialized to 0
int b[10]{};
// You can also assign different values to different elements of the array
b[0] = 6;
b[8] = 2;
// You can then use the array elements in operations
int c = b[0] * b[8];
If you want array like structure without compile time defined size, then use std::vector.
// An empty vector of ints
std::vector<int> d;
// A simple int
int e = 5;
// Push 2 values to the end of the vector
d.push_back(2);
d.push_back(e);
// Use the members for operations
int f = d.at(0) * d.at(1);
Since you've now described the problem you're trying to solve instead of just the problem with the solution you came up with:
You don't need to invent variable names or use arrays to compute averages and maximums.
Here's an example of how you can compute an average of the numbers a user inputs:
float sum = 0;
int elements = 0;
float input = 0;
while (cin >> input)
{
sum += input;
elements += 1;
}
std::cout << "Average: " << sum / elements << std::endl;
It's easy to expand this to also keep track of the maximum value so far.
To expand to the average and maximum of a number of series, add another loop "around" it.

Why I am getting Time Limit Exceeded? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting Time Limit Exceeded on submitting this question
Question:
Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
on each path the next number is located on the row below, more precisely either
directly below or below and one place to the right;
the number of rows is strictly positive, but less than 100
all numbers are positive integers between O and 99.
My Code:
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int trian(int i,int j);
long long int n,a[100][100];
int main()
{
long long int t,i,j,v,k;
scanf("%lld",&t);
for(i=0;i<t;i++)
{
scanf("%lld",&n);
for(j=0;j<n;j++)
{
for(k=0;k<j+1;k++)
{
scanf("%lld",&a[j][k]);
}
}
v=trian(0,0);
printf("%lld\n",v);
}
}
int trian(int i,int j)
{
if(i>=n)
return 0;
else
return (a[i][j]+(std::max(trian(i+1,j),trian(i+1,j+1))));
}
Why I am getting Time Limit Exceeded?
Consider this triangle (ignore the numbers):
1
2 3
There are 2 possible paths to take here. Let's add a row:
1
2 3
4 5 6
The 4 can only be reached via a path that ends directly above, the 5 has two paths which can reach it, the 6 can only be reached from the path previously ending left above of it. We now have 4 possible paths. Another row:
1
2 3
4 5 6
7 8 9 0
That's 8 possible paths. Do you see a pattern? Let's describe the path straight down to 7, starting from 1:
D = DOWN
R = DOWN AND RIGHT
DDD
The (single) path to 0:
RRR
Since in each step you go down one row, you can only chose between the two possibilities number of rows - 1 times, thus giving you:
2^(number of rows - 1) possible paths
With 100 rows, that's alot. Your code tries to compute each of these paths separately. Assuming computing 1 path takes 1 nanosecond (which would be blazing fast) computing them all would take more than 2 * 10^16 years. Well, ...
Time Limit Exceeded
So you now know that you cannot just compute every possible path and take the maximum. The main issue is the following:
1
2 3
4 5 6
One path to the 5 is 1 + 3 + 5, the path to the 6 is 1 + 3 + 6. Your code computes each path separately, thus 1 + 3 will be computed twice. If you save that result, you'll get rid of most of the unnecessary computations.
How could you store such results? Well, 1 + 3 is the computation of the path arriving at 3, so store it there. What if a number (say 5) can be reached by multiple paths?
5 could be reached via 1 + 2 + 5 or 1 + 3 + 5.
Any path going through the 5 will give a higher result if it wen't through the 3 first, so only remember this path (and ignore the path through the 2, it's useless now).
So, as an algorithm:
For each row, starting at row 1 (not the first, but the second): For each entry: Calculate the maximum of the entries left above (if available) and directly above (if available) and store the result + the entry's value as new value for the entry. Then, find the maximum of the last row.

Wrong Answer in SUBSEQ spoj

I was solving Counting Subsequence Problem in spoj, but getting Wrong Answer. here is the link http://www.spoj.com/problems/SUBSEQ/
Here is my code
#include<stdio.h>
#include<cmath>
#include<algorithm>
int main(){
int t,n;
scanf("%d",&t);
while(t-->0){
scanf("%d",&n);
long arr[n+1];
for(int i=0;i<n;i++){
scanf("%ld",&arr[i]);
}
long sum=arr[0];
int start=0;
long ans=0;
for(int i=1;i<=n;i++){
while(sum>47 && start<i-1){
sum-=arr[start];
start++;
}
if(sum==47)
ans+=1;
if(i<n)
sum+=arr[i];
}
printf("%ld\n",ans);
}
}
Please help me find the error ..
You code will fail the following test case (at least):
1
4
47 -47 48 -1
Your programs gives the answer as 1, where as the answer should be 3, where 3 sequences as follows:
47 -47 48 -1 [The entire sequence]
47 [1st element only]
48 -1 [3rd plus 4th elements]
So, clearly, you've got bugs.
PS: BTW, why are you declaring an array of n+1 items: long arr[n+1]; when you are never going to reference arr[n]? (in fact that item won't even exist)
[Edit]#: Adding explanation for the above use case
How about this - Its easier than you think :-)
Scan the numbers serially. For each number encountered, add it to sum found so far.
Keep a map of number of times the sum (so far) has been found.
Now, to make a total of 47, all we need is to find a number, which when subtracted from the sum so far should give number 47. This is required because if we subtract such number from sum found so far, it would yield 47 obtained from summation of some sequence(s) of contiguous numbers.
Take the above example, 47 -47 48 -1
Initialize a map with number 0 having count = 0 (That's to say that we have found no sum so far exactly once - since we are at the begining)
Scanning the list from the beginning, take number 47, sum so far, say, s = 47. We do 2 things:
map(47) = 1 (since we've found sum so far = 47 for first time).
Now, we need to find number of times, we've can find s-47 = 0 (which is 1). So, answer so far = map(0) = 1
Take next number, -47. Sum so far, s = 0
map(0) = 1 so far, so no map(0) becomes = 2
We need to find number of occurrences of s-47 = -47. Which = 0. So answer so far = answer so far + 0 (remains = 1)
Take next number, 48, sum so far, s = 48
map(48) = 1
We need to find number of occurrences of s-48 = -1. Which = 0. So answer so far = answer so far + 0 (remains = 1)
Take last number, -1, sum so far, s = 47
map(47) = 1 (in step 2.1), so now map(47) becomes = 2
We need to find number of occurrences of s-47 = 0. Which = 2 (in step 3.1). So answer so far = answer so far + 2 = 3
So final answer = 3
It should be fairly trivial to code this.