I am trying to create a function calculating the net present worth(NPW) of each project, the project which has the highest NPW will be our choice.
The program works fine for one project, if I enter more than one project it prints only the last project results repeated as much as the number of the projects.
code:
#include <iostream>
#include <cmath>
using namespace std;
void npwMethod(int nproj,int *pv,int *n, int *oc, int *ai,int *sv ,float marr){
float npw[nproj], sum[nproj];
for(int i=1;i<=nproj;i++){
for(int j=1;j<=n[i];j++){
sum[i]+=(oc[j]*(pow(1+marr,-j)));
}
for(int j=1;j<=n[i];j++){
sum[i]+=(ai[j]*(pow(1+marr,-j)));
}
npw[i]=pv[i]+sv[i]*(pow(1+marr,-n[i]))+sum[i];
}
for(int i=1;i<=nproj;i++){
cout<<"NPW"<<i<<"="<<npw[i]<<endl;
}
}
int main() {
int nProj,methodNum, *OC, *AI;
float MARR;
cout<<"Enter the number of projects please:";
cin>>nProj;
int *PV=new int[nProj], *N=new int[nProj], *SV=new int [nProj];
for(int i=1;i<=nProj;i++){
cout<<"------Project"<<i<<"------\n";
cout<<"PV"<<i<<":";
cin>>PV[i];
cout<<"n"<<i<<":";
cin>>N[i];
OC=new int[N[i]], AI=new int [N[i]];
for(int j=1;j<=N[i];j++){
cout<<"OC"<<j<<":";
cin>>OC[j];
}
for(int j=1;j<=N[i];j++){
cout<<"AI"<<j<<":";
cin>>AI[j];
}
cout<<"SV"<<i<<":";
cin>>SV[i];
}
cout<<"-------------------\nMARR:";
cin>>MARR;
MARR=MARR/100;
cout<<"------RESULTS------\n";
npwMethod(nProj, PV, N, OC, AI, SV, MARR);
}
Inputs:
Enter the number of projects please:2
------Project1------
PV1:-1000
n1:2
OC1:-200
OC2:-300
AI1:0
AI2:0
SV:2000
------Project2------
PV1:-1000
n1:2
OC1:-200
OC2:-300
AI1:500
AI2:0
SV:2000
-------------------
MARR:10
Expected output:
NPW1:223.14
NPW2:677.686
Could anyone help solving this issue please?
Your problem boils down to these lines:
int* OC;
for(int i=1; i <= nProj; i++){
OC = new int[N[i]];
for(int j=1; j <= N[i]; j++){
cout << "OC" << j << ":";
cin >> OC[j];
}
}
npwMethod(nProj, PV, N, OC, AI, SV, MARR);
with OC = new int[N[i]], you override the value of OC from the previous project. Same happens for AI. You need your OC to be an array of arrays. This is a lot easier when you use std::vector. Then you could do something like this:
int main() {
std::vector<std::vector<int>> OCs;
for(int i=1; i <= nProj; i++){
OCs.emplace_back();
OC = OCs.back();
for(int j=1; j <= N[i]; j++){
cout << "OC" << j << ":";
int oc;
cin >> oc;
OC.push_back(oc);
}
}
npwMethod(nProj, PV, N, OCs, AI, SV, MARR);
}
void npwMethod(..., std::vector<std::vector<int>> const& oc, ...) {
for(int i=1; i<=nproj; i++){
for(int j=1 ;j<=n[i]; j++){
sum[i] += oc[i][j]*...;
}
}
}
Related
for example, I have to take input in the format:
2 // no of test cases
7 // n->size of an array
9 7 5 9 2 20 3 //n array elements
5 // second test case array size
4 5 8 96 6 // second test case array elements
I don't know what to write in the main function.
void sort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int current =arr[i];
int j;
for(j=i-1;j>=0;j--)
{
if(current<arr[j])
{
arr[j+1]=arr[j];
}
else
{
break;
}
}
arr[j+1]=current;
}
}
int main(){
// what should I write in the main func to test my problem for t no of times
// I have to take all inputs first then print the sorted arrays given by the user
// separated by space and new line for the next sorted array
}
I think this what you want.
const int N = 10;
int main(){
int t, n, arr[N];
cin >>t;
for(int T;T<t;++T){
cin >>n;
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Make sure to put the value if N is the maximum possible size of the array. Or you can declare the array as a dynamic array with the entered n (or use one of the STL like vector)
for example:
int main(){
int t, n;
cin >>t;
for(int T;T<t;++T){
cin >>n;
int * arr = new int [n];
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Or by using Vector:
#include<vector>
using namespace std;
//your sort func here, but make sure to change it to have a vector instead of an array
int main(){
int t, n;
vector<int>arr;
cin >>t;
for(int T;T<t;++T){
arr.clear();
cin >>n;
arr.resize(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
PS: I would recommend to see websites like codeforces, Hackerrank and others to practice on competitive programming question which contains a lot of question that will help (If you're interested)
int main()
{
int t; // number of test cases
std::cin >> t;
while (t--) // repeat t times
{
// what you had before
}
}
to test you can
define an input and a desired output, i.e an array "unsorted" and how it SHOULD look like after sorted
define a method that sorts input "a" and allows you to verify that by eather returning the sorted array or modifying the reference given as parameter.
defined a compare method that takes x1 and x2 as parameter and returns a bool indicating if the operation failed or no. x1 can be the desired sorted array and x2 the array returned from step1
loop in a for with DIFFERENT unsorted arrays and theis according sorted values...
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
cout << endl;
}
return 0;
}
I think this will work
this is a code example for what I mean
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int numOfTest = 0;
std::vector<int>vec;
std::cin>>numOfTest ;
for(int j=; j<=numOfTest; ++j) // loop for num of tests
{
int n=0;
for(int i=0; i<n; ++i) // loop for num of veriabels in one test
{
int var=0;
std::cin >> var;
vec.push_back(var);
}
// option one
int* arr = new int[n] ;
std::copy(vec.begin(),vec.end(),arr);
sort(arr, n);
//option two
sort(&vec[0], n);
//option three
sort(vec.data(), n);
for(int f=0; j<=n ++j)
{
std::cout << arr[f] << " "; // print the sorted array;
}
delete [] arr;
}
return 0;
}
if your choosing option two or three you can using range base loop instead of for loop:
it will look like this:
for(auto& e: vec)
{
std::cout << e << " ";
}
[![enter image description here][1]][1]
This is what I have tried out but whenever I run the program it crashes and says error, although it compiles correctly. It asks me to enter department number but after that doesn't show me any output
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int STDTs = 25;
const int DEPTs = 7;
void initializeGPAs(double gpa[][DEPTs])
{
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
gpa[i][j]=(10+rand()%31)/10;
}
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
sum+=gpa[j][i];
deptAvg[i]=double(sum/STDTs);
}
}
int StdsOnProbationCount(double gpa[][DEPTs])
{
int ctr=0;
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
if(gpa[i][j]<2)
ctr++;
return ctr;
}
int StdsOnProbationCountinDeptX(double gpa[][DEPTs], int x)
{
int ctr=0;
for(int i=0;i<STDTs;i++)
if(gpa[i][x-1]<2)
ctr++;
return ctr;
}
void showReport(double gpa[][DEPTs],string dept_names[], double deptAvg[], int ctr1, int ctr2, int x)
{
cout<<endl;
for(int i=0;i<DEPTs;i++)
{
cout<<'\t'<<dept_names[i]<<" ";
}
cout<<endl;
for(int i=0;i<STDTs;i++)
{
cout<<"Student "<<i+1<<": ";
for(int j=0;j<DEPTs;j++)
cout<<gpa[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(int t=0;t<DEPTs;t++)
cout<<"Dept Avg.: "<<deptAvg[t]<<" ";
cout<<endl<<endl;
cout<<"Total number of students who are on probation is: "<<ctr1;
cout<<endl;
cout<<"Number of students who are on probation in "<<dept_names[x-1]<<" Dept. is "<<ctr2;
}
int main()
{
double gpa[STDTs][DEPTs];
int ctr1, ctr2, x;
double deptAvg[DEPTs];
string dept_names[DEPTs]={"MATH","STAT","COMP","PHYS","CHEM","BIOL","GEOL"};
initializeGPAs(gpa);
computeDeptAvg(gpa, deptAvg);
ctr1 = StdsOnProbationCount(gpa);
cout<<"Enter Department Number [1 to 7]: ";
cin >> x;
ctr2 = StdsOnProbationCountinDeptX(gpa, x);
showReport(gpa, dept_names, deptAvg, ctr1, ctr2, x);
return 0;
}
edit: I figured everything out but my problem seems to be in this function because it displays zeroes for all the department averages
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
{
sum+=gpa[j][i];
deptAvg[j]=double(sum/STDTs*1.0);
}
}
}
I'll consider only your computeDeptAvg function.
Your sum variable should be of type double, declaring it as an int makes all of your calculations (specifically the sum+=gpa[j][i] and sum/STDTs, which is an integer division) prone to truncating errors.
You nested the two loops in the wrong order: You should sum the scores of all the students in a particular department in order to calculate the average of that department. Besides, deptAvg[j] is overwritten every time the outer loop is executed.
You have declared gpa in main as a double gpa[STDTs][DEPTs];, but in your loops you are using gpa[j][i], where j is in the range [0, DEPTs) and i in [0, STDTs).
A modified version could be:
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int d = 0; d < DEPTs; d++)
{
double sum = 0.0;
for(int s = 0; s < STDTs; s++)
{
sum += gpa[s][d];
}
deptAvg[d] = sum / STDTs;
}
}
This is a quicksort code based on the algorithm in the book(neapolitan). the results are true but at the end of debugging it has a run time error and I can't fix it. the error is heap corruption please help me to fix or improve it(if it's wrong). thanks for all answers.
#include <conio.h>
#include <iostream>
using namespace std;
int partition( int *A, int p, int q)
{
int x = A[p];
int i = p;
for (int j = p+1; j <= q; j++)
{
if (A[j] <= x)
{
i++;
swap (A[j],A[i]);
}
}
swap (A[i],A[p]);
return i;
}
void Quick_sort( int *A, int p, int r)
{
int q;
if( p<r)
{
q = partition(A,p,r);
Quick_sort( A, p, q-1);
Quick_sort( A, q+1, r);
}
}
void main()
{
int n;
cout << "How many elements do you want to sort(quicksort)? ";
cin >> n;
int *A;
A = new int [n];
for (int k=0;k<n;k++)
{
cout << "A["<<k<<"]= ";
cin >> A[k];
}
cout << endl;
Quick_sort(A,1,n);
cout << "\nsorted array: " <<endl;
for (int i = 1; i < n+1; i++)
{
cout << A[i]<<"\t";
}
cout << endl;
delete A;
}
the question is: Why this code has an error? How many errors do you see in this?
You have a so called "fence post error", where your array indices are off by one.
The lines
A =(int *) malloc(n * sizeof(int));
and
for (int k=1;k<=n;k++)
{
cout << "A["<<k<<"]= ";
cin >> A[k];
}
propably cause the error, you start the index with 1 instead of 0. The code should be
for (int k=0;k<n;++k)
{
cout << "A["<<k<<"]= ";
cin >> A[k];
}
note that you also have the same error in the second for-loop
The code should be: for (int k=1;k<=n;k++) instead of for(int k=0;k<n;++k)
and also change the line:
A = new int [n]; with A = new int [n+1];
I debug it with no errors!
good luck
I've just programmed the following simple merge function in mergesort which follows exactly the one written in CLRS book.
#include<iostream>
#include<vector>
#include<limits>
using namespace std;
//Define the numerical positive infinity
const int INFP = numeric_limits<int>::max();
void MERGE(vector<int> A, int p, int q, int r){
//Create the size of left and right array
int n1 = q-p+1;
int n2 = r-q;
//Create the left array
vector<int> L(n1+1);
for(int i=0; i<n1;i++){
L[i] = A[i];
}
L[n1] = INFP; //Insert sentinel here!
//Create the right array
vector<int> R(n2+1);
for(int i=0; i<n2;i++){
R[i] = A[q+i+1];
}
L[n2] = INFP; //Insert sentinel here!
int i = 0;
int j = 0;
for(int k = 0; k <= r; k++){
if(L[i]<=R[j]){
A[k] = L[i];
i=i+1;
}
else{
A[k] = R[j];
j=j+1;
}
}
for(int m=0;m<4;m++){
cout<< A[m] << " ";
}
cout << endl;
}
int main(){
//test for merge function:
vector<int> A(4);
A[0]=1;
A[1]=3;
A[2]=2;
A[3]=4;
MERGE(A,0,1,3);
for(int m=0;m<4;m++){
cout<< A[m] << " ";
}
cout << endl;
return 0;
}
However, it gave me the following print out, which really confused me:
1 2 3 4
1 3 2 4
I don't know if it's the problem of the void function that I can't use void function for vectors or something else.
Really hope someone can help me out. Thanks!
It's because you pass the vector by value, meaning you modify a local copy. Pass it by reference instead.
I have this code to do permutations of a string.
#include <iostream>
#include <string.h>
using namespace std;
/* Prototipo de funciĆ³n */
void Permutaciones(char *, int l=0);
void sort(string scadena[]);
//array global to copy all permutations and later sort
string array[900000];
int m=0;
int main() {
int casos;
cin>>casos;
char palabra[casos][13];
for(int i=0;i<casos;i++)
cin>>palabra[i];
for(int i=0;i<casos;i++){
m=0;
Permutaciones(palabra[i]);
sort(array);
}
sort(array);
system("pause");
return 0;
}
void sort(string scadena[]){
string temp;
for(int i=0;i<m;i++){
for(int j=i+1;j<m;j++){
if(scadena[i]>scadena[j]){
temp=scadena[i];
scadena[i]=scadena[j];
scadena[j]=temp;
}
}
}
for(int i=0;i<m;i++){
for(int j=1;j<m;j++){
if(scadena[i]==scadena[j] && j!=i){
for(int k=j;k <m; k++){
scadena[k]=scadena[k+1];
}
m--;
j--;
}
}
}
for(int i=0;i<m;i++){
cout<<scadena[i]<<endl;
}
}
void Permutaciones(char * cad, int l) {
char c; /* variable auxiliar para intercambio */
int i, j; /* variables para bucles */
int n = strlen(cad);
for(i = 0; i < n-l; i++) {
if(n-l > 2){
Permutaciones(cad, l+1);
}
else {
array[m]=cad;
m++;
}
/* Intercambio de posiciones */
c = cad[l];
cad[l] = cad[l+i+1];
cad[l+i+1] = c;
if(l+i == n-1) {
for(j = l; j < n; j++){
cad[j] = cad[j+1];
}
cad[n] = 0;
}
}
}
And the code generates all permutations fine, and later sorted the array and it works fine. But when i am intenting remove the repeated strings, the code show me somethings repeated, and not sorted.
Who can say me what is my error?
You could have accomplished it easier using standard library:
#include <algorithm>
using namespace std;
int main() {
int a[] = {1, 2, 5, 6, 7};
int n = 5;
do {
// print array a
} while (next_permutation(a, a + n));
}
Unless the task was to implement it on your own. And of course make sure your array is sorted before you try to permutate it in this way, otherwise you will miss some permutations.
HERE, is a simplest code for generating all combination/permutations of a given array without including some special libraries (only iostream.h and string are included) and without using some special namespaces than usual ( only namespace std is used).
void shuffle_string_algo( string ark )
{
//generating multi-dimentional array:
char** alpha = new char*[ark.length()];
for (int i = 0; i < ark.length(); i++)
alpha[i] = new char[ark.length()];
//populating given string combinations over multi-dimentional array
for (int i = 0; i < ark.length(); i++)
for (int j = 0; j < ark.length(); j++)
for (int n = 0; n < ark.length(); n++)
if( (j+n) <= 2 * (ark.length() -1) )
if( i == j-n)
alpha[i][j] = ark[n];
else if( (i-n)== j)
alpha[i][j] = ark[ ark.length() - n];
if(ark.length()>=2)
{
for(int i=0; i<ark.length() ; i++)
{
char* shuffle_this_also = new char(ark.length());
int j=0;
//storing first digit in golobal array ma
ma[v] = alpha[i][j];
//getting the remaning string
for (; j < ark.length(); j++)
if( (j+1)<ark.length())
shuffle_this_also[j] = alpha[i][j+1];
else
break;
shuffle_this_also[j]='\0';
//converting to string
string send_this(shuffle_this_also);
//checking if further combinations exist or not
if(send_this.length()>=2)
{
//review the logic to get the working idea of v++ and v--
v++;
shuffle_string_algo( send_this);
v--;
}
else
{
//if, further combinations are not possiable print these combinations
ma[v] = alpha[i][0];
ma[++v] = alpha[i][1];
ma[++v] = '\0';
v=v-2;
string disply(ma);
cout<<++permutaioning<<":\t"<<disply<<endl;
}
}
}
}
and main:
int main()
{
string a;
int ch;
do
{
system("CLS");
cout<<"PERMUNATING BY ARK's ALGORITH"<<endl;
cout<<"Enter string: ";
fflush(stdin);
getline(cin, a);
ma = new char[a.length()];
shuffle_string_algo(a);
cout<<"Do you want another Permutation?? (1/0): ";
cin>>ch;
} while (ch!=0);
return 0;
}
HOPE! it helps you! if you are having problem with understanding logic just comment below and i will edit.