issues with Storing to array [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was testing one of my classes, but for some reason I can't seem to cast an intiger from a 2d array to double. Here is my (very simplified) code:
In main.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h contains class declaration only, so I believe it is irrelevant. Here is my trajectories.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (&currentCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
Please note that removing command traj.AddCoordinates(coords) will make the problem disappear. Am I passing the array correctly to the function?

The problem is in your constructor NPCTrajectory. Replace npoints with loop variable i. The following code:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
should be like:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
Because of this incorrect allocation, you are getting error (segmentation fault) in AddCoordinates function when you try to access points[i][0] with i=0 (assuming you are giving npoints>0 in NPCTrajectory).

Related

0/1 Knapsack problem using Dynamic Programming, Top-Down Approach [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 1 year ago.
Improve this question
Greeting everyone, I'm trying to solve 0/1 Knapsack problem using the Dynamic Programming Top-Down Approach. I'm pretty sure that most of my logic is correct, my code is compiling successfully. But, it's not giving the proper/correct output that is needed.
For Instance, suppose weight[] has inputs as 10,20,30 and it's corresponding value[] has 60,100,120. The max weight that the Knapsack can hold onto is 50. The max profit should be 220, but my code is giving me the answer 280 instead. Please help me, here's my piece of code:-
#include<bits/stdc++.h>
using namespace std;
void knapsack(vector<int>& weight, vector<int>& value, int w, int n){
vector<vector<int>> t;
for(int i=0;i<n+1;++i){
vector<int> temp;
for(int j=0;j<w+1;++j){
int x =0;
temp.push_back(x);
}
t.push_back(temp);
temp.clear();
}
for(int i=1;i<n+1;++i){
for(int j=1;j<w+1;++j){
if(weight[i-1]<=w){
t[i][j] = max(value[i-1]+t[i-1][w-weight[i-1]], t[i-1][j]);
}
else{
t[i][j] = t[i-1][j];
}
}
}
cout<<"Max Profit: "<<t[n][w];
// return final;
// vector<int> oneDimVector;
// for(int i = 0; i < n+1; i++){
// for(int j = 0; j < w+1; j++){
// oneDimVector.push_back(t[i][j]);
// }
// }
// vector<int>::iterator maxElement;
// maxElement = max_element(oneDimVector.begin(), oneDimVector.end());
// cout<<"Max Profit: "<<*maxElement;
}
int main(){
int n;
int w;//Total weight of knapsack
cin>>n;
cin>>w;
vector<int> weight;
vector<int> value;
for(int i=0;i<n;++i){
int x;
cin>>x;
weight.push_back(x);
}
for(int i=0;i<n;++i){
int x;
cin>>x;
value.push_back(x);
}
knapsack(weight,value,w,n);
}
I again debugged my code, I had to change one variable which I had written wrong in the following line of code:-
t[i][j] = max(value[i-1]+t[i-1][w-weight[i-1]], t[i-1][j]);
here, it should be:-
t[i][j] = max(value[i-1] + t[i-1][ j - weight[i-1]], t[i-1][j]);

Stop working when running [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 5 years ago.
Improve this question
i wrote this code for my university project but it stop working when i try to run it.
can any one please help me where the problem is?
i guess its the pointers but i dont know where its wrong
for t and z if u want to try it use 20 and 5
and when i enter them it stop working instead of giving me outputs
it should give 2 .txt file including some numbers
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int t;
int z;
double deltaz;
double deltat;
double beta;
double mv=0;
ofstream out1("Time-setllment.txt");
ofstream out2("isochrones.txt");
cout<<"Enter time step(>9&integer only):";
cin>>t;
cout<<endl<<"Enter height step(integer only):";
cin>>z;
cout<<endl;
double **u = new double * [z+1];
for (int i=0;i<z;i++)
u[i]=new double [t+1];
double *s = new double [t+1];
mv = (0.00000003*365*24*3600)/(2*10);
deltaz = 20/z;
deltat = 50/t;
beta = (2*deltat)/(deltaz*deltaz);
if (beta>0.5)
cout<<"Beta is more than 0.5 :|"<<endl;
else
{
for (int i=0;i<z+1;i++)
{
if (i==0 || i==z)
{
for (int j=0;j<t+1;j++)
u[i][j] = 0;
}
else
{
u[i][0]=70-3.5*(i*deltaz);
}
}
for (int j=1;j<t;j++)
{
for (int i=1;i<z;i++)
{
u[i][j] = u[i][j-1]+beta*(u[i-1][j-1]+u[i+1][j-1]-2*u[i][j-1]);
}
}
for (int j=1;j<t+1;j++)
{
double sigmau=0;
for (int i=1;i<z;i++)
{
sigmau +=u[i][j];
}
s[j]=mv*(35*20-deltaz*((u[0][j]+u[z][j])/2+sigmau));
}
out1<<"Time \t Settlment \n";
for (int j=1;j<t+1;j++)
{
out1<<j*deltat<<"\t"<<s[j]<<"\n";
}
out2<<"Depth \t";
for (int j=0;j<t+1;j++)
{
out2<<"t(year)="<<j*deltat<<"\t";
}
out2<<"\n";
for (int i=0;i<z+1;i++)
{
out2<<i*deltaz<<"\t";
for (int j=0;j<t+1;j++)
{
out2<<u[i][j]<<"\t";
}
}
for (int i=0;i<z+1;i++)
delete []u[i];
delete []u;
delete []s;
}
return 0;
}
You have an error in data allocation:
double **u = new double * [z+1];
for (int i=0;i<z;i++)
You actually want to change this to:
double **u = new double * [z+1];
for (int i=0;i<z+1;i++)

Skipped condition and I don't know why [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I was debugging this, and debugger skipped the last 'if' even 'sum' was equal to 'n' and jump straight to 'else', I don't know why. Please help.
P/s: Can I use dynamic array to increase the mobility of my program?
#include <iostream>
#include <math.h>
using namespace std;
int exponent_of_10(); // set position for digits
int exponent_of_10(int a, int b){
for(int j = b; j>0;j--)
{
a *= 10;
}
return a;
}
main() //check if the number was palindromic
{
int n;
int a[6]={0,0,0,0,0,0};
int i = 0;
int temp;
int S;
cout<< "Input n (maximum of 6 digits): ";
cin>> n;
do
{
if(n<1)
{break;}
temp=n%10;
a[i]=temp;
n=(n-temp)/10;
i++;
}
while (n!=0);
int sum = 0;
for(int j=0; j<=5; j++)
{
exponent_of_10(a[j],j);
S = exponent_of_10(a[j],j);
if (S==0)
{break;}
sum +=S;
}
if(sum==n)
{
cout<< "Congratz, this is PALIDROMIC NUMBER !!";
}
else
cout<< "Sad life, this is NOT palidromic number";
return 0;
}
When the code exits the do ... while() loop, n is 0. For the test in the if to be meaningful, the code should save the original value of n somewhere and compare sum to that original value.

How to make all array elements accessible [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to make the elements of an array accessible, but I've had no success so far. This is the code, and I've created it due to the given assignment.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Matrix_1D
{
private:
int *p2values;
int num_elements;
public:
Matrix_1D(int *p2v, int n); // CTOR
~Matrix_1D(); // DTOR
void show();
};
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
Matrix_1D::~Matrix_1D()
{
delete [] p2values;
}
void Matrix_1D::show()
{
for(int i=0; i<num_elements; i++)
cout << p2values[i] << endl;
}
int main()
{
int array_a[] = {5,3,5};
Matrix_1D fkt_1D_a(array_a, sizeof(array_a)/sizeof(int));
fkt_1D_a.show();
system("pause");
return 0;
}
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
As you state the sizeof p2v is the size of the pointer so you have no idea how large the array is. Instead, use the parameter that is passed in and don't overwrite it:
Matrix_1D::Matrix_1D(int *p2v, int n)
{
// you don't need the first line at all.
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
The proper C++ way to get the size of your int array is to use a template:
template <typename T, size_t N>
size_t size(T (&)[N]) {
return N; // size of array
}

OpenMp example program [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to parallelize a program with OpenMP and I don't have any idea. The code below is a similar (very) semplified problem. I have a class whose attributes are a vector and its lenght. The method 'work' calculate each new element v[i] of the vector as the average value of the one before and the one after (considering periodic boundaries, ie element 0 is the average of element 1 and element (len-1)).
class:
#include<vector>
#include<iostream>
class A{
private:
std::vector<int> v;
int len;
public:
A(): len(0), v(0){
v[0] = 0;
}
A(unsigned n): len(n), v(n){
for(int i = 0; i < len; i++)
v[i] = 2*(i+1);
}
void work(){
std::vector<int> temp(len);
for(int i = 0; i < len; i++)
temp[i] = (v[((i-1+len)%len)] + v[((i+1)%len)]) / 2;
v.swap(temp);
}
void out(){
for(int i = 0; i < len; i++)
std::cout << v[i] << " ";
std::cout << std::endl;
}
~A(){}
};
main:
#include <iostream>
#include "omp.h"
#include "class.cpp"
int main () {
A a(5);
for(int i = 0; i < 10; i++){
a.work();
}
a.out();
return 0;
}
The method work is called multiple times. Can someone write me few lines of code to explain what to do?
I have the solution, in the method work of the class you have to write before the cycle:
#pragma omp parallel for
that's all!!!