Itrying to find the path of a node in a binary tree by a vector function but I am getting only 2 values from the starting node in output of the vector - c++17

I am trying to find the path of a node in a binary tree by a
vector function but I am getting only 2 values from the of
starting of the node in output of the vector
like I am trying to find the path of the node 10 and my output
would be in the following way---(1 3 7 9 10),but I am getting
only (1 3) in the output
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
vector<int> path(node *root, int x)
{
static vector<int> v;
if (root == NULL)
{
return v;
}
v.push_back(root->data);
if (root->data == x)
{
v.push_back(x);
return v;
}
path(root->left, x);
path(root->right, x);
v.pop_back();
return v;
}
int main()
{
struct node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->left->right->left = new node(11);
root->right->left = new node(6);
root->right->right = new node(7);
root->right->right->right = new node(9);
root->right->right->right->right = new node(10);
int x = 10;
vector<int> v = path(root, x);
cout << v.size();
cout << endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
return 0;
}

Related

Segmentation Fault - Ceres Solver

I am trying to achieve solution for a Multilateration problem. The input data i have are Global pose of the landmarks and distances from it.
My costfunction is following
struct CostFunctor {
// Initializing constant parameters
CostFunctor(std::vector<double>& a_n, float d_n)
: a_n_(a_n), d_n_(d_n) {}
/*
Residual
\f$f_n(x) = ((a_{n_1} - x_1)^2 + (a_{n_2} - x_2)^2 + (a_{n_3} - x_3)^2 - d_n^2)\f$
*/
template <typename T>
bool operator()(const T* const x,
T* residual) const {
residual[0] = ((T(a_n_[0]) - x[0]) * (T(a_n_[0]) - x[0])
+ (T(a_n_[1]) - x[1]) * (T(a_n_[1]) - x[1])
+ (T(a_n_[2]) - x[2]) * (T(a_n_[2]) - x[2])
- (T(d_n_) * T(d_n_))
);
return true;
}
private:
const std::vector<double>& a_n_;
const float d_n_;
};
And the main code is
std::vector<double> solveProblem(std::vector<double> &position, std::vector<std::vector<double>> &global_pose, std::vector<float> &dists)
{
std::vector<double> x = {0.0, 0.0, 0.0};
problem.AddParameterBlock(x.data(), 3);
//ceres::Lossfunction *loss_function = NULL;
for (unsigned int i = 0; i < dists.size(); i++) {
ceres::CostFunction *cost_function =
new ceres::AutoDiffCostFunction<CostFunctor, 1, 3>(
new CostFunctor(global_pose[i], dists[i]));
std::cout << "in solve problem for" << std::endl;
problem.AddResidualBlock(cost_function,
NULL,
x.data());
}
// Run the solver
options.max_num_iterations = 50;
options.minimizer_progress_to_stdout = true;
ceres::Solve(options, &problem, &summary);
std::cout << summary.FullReport() << std::endl;
double* dPos = x.data();
for (unsigned int i = 0; i < 3; i++) {
position[i] = *dPos++;
}
return position;
}
However, i get the segmentation fault error.
Edit
I run this file as a ROSnode, which subscribes to a topic to get the input data (i.e global_pose, dists)
The solver runs first time successfully and then throws segmentation error.
Parth

add function is not working properly in Polynomial using linked list

I can't find any error in this code, please can anyone help me out with this.
please provide the whole code by debugging the given code.
I'm having a problem in adding two polynomials otherwise everything is fine.
I wasted my whole week in figuring out this bug but can't be able to find it.
so I will be happy if anyone can help me, please
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct Node
{
int coeff;
int exp;
struct Node *next;
} *poly = NULL, *poly2 = NULL;
void create()
{
struct Node *t, *last = NULL;
int num, i;
printf("Enter number of terms");
scanf("%d", &num);
printf("Enter each term with coeff and exp\n");
for (i = 0; i < num; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
scanf("%d%d", &t->coeff, &t->exp);
t->next = NULL;
if (poly == NULL)
{
poly = last = t;
}
else
{
last->next = t;
last = t;
}
}
}
void create2()
{
struct Node *t, *last = NULL;
int num, i;
printf("Enter number of terms");
scanf("%d", &num);
printf("Enter each term with coeff and exp\n");
for (i = 0; i < num; i++)
{
t = (struct Node *)malloc(sizeof(struct Node));
scanf("%d%d", &t->coeff, &t->exp);
t->next = NULL;
if (poly2 == NULL)
{
poly2 = last = t;
}
else
{
last->next = t;
last = t;
}
}
}
void Display(struct Node *p)
{
while (p)
{
printf("%dx%d +", p->coeff, p->exp);
p = p->next;
}
printf("\n");
}
long Eval(struct Node *p, int x)
{
long val = 0;
while (p)
{
val += p->coeff * pow(x, p->exp);
p = p->next;
}
return val;
}
void add(struct Node *p, struct Node *q)
{
struct Node *sum = (struct Node *)malloc(sizeof(struct Node));
while (p && q)
{
if (p->exp > q->exp)
{
sum->exp = p->exp;
sum->coeff = p->coeff;
p = p->next;
if (p)
{
sum->next = (struct Node *)malloc(sizeof(struct Node));
sum = sum->next;
}
}
else if (p->exp < q->exp)
{
sum->exp = q->exp;
sum->coeff = q->coeff;
q = q->next;
if (q)
{
sum->next = (struct Node *)malloc(sizeof(struct Node));
sum = sum->next;
}
}
else
{
sum->exp = p->exp;
sum->coeff = p->coeff + q->coeff;
q = q->next;
p = p->next;
if (p && q)
{
sum->next = (struct Node *)malloc(sizeof(struct Node));
sum = sum->next;
}
}
}
while (p)
{
sum->next = (struct Node *)malloc(sizeof(struct Node));
sum = sum->next;
sum->exp = p->exp;
sum->coeff = p->coeff;
p = p->next;
}
while (q)
{
sum->next = (struct Node *)malloc(sizeof(struct Node));
sum = sum->next;
sum->exp = q->exp;
sum->coeff = q->coeff;
q = q->next;
}
sum->next = NULL;
Display(sum);
}
int main()
{
create();
create2();
Display(poly);
//printf("\n");
Display(poly2);
//printf("\n");
add(poly, poly2);
return 0;
}

Round Robin Algorithm Using Circular Linked List

Use a circular singly linked list to implement Round Robin process scheduling algorithm in which
each process is provided a fixed time (quantum) to execute and is pre-empted after that time period
to allow the other process to execute. Assume a set of ‘n’ processes are ready for execution.
Read the time quantum and for each of the processes, read the total execution time.
Name the processes as ‘A’, ‘B’ and so on in sequence. Each node should contain the name
of the process, its total execution time and the remaining execution time. If a process
completes its execution, remove it from the list after displaying its name and the
completion time.
Input format:
First line contains the value of ‘n’, the number of processes
Second line contains the time quantum
The remaining lines contain the total execution time of the processes in order.
5
2
6
3
7
5
1
Output:
E 9
B 12
A 18
D 21
C 22
#include <iostream>
using namespace std;
class node
{
public:
char name;
int tm;
int rt;
node *next;
};
class rr
{
public:
node * Head = NULL;
int j = 65;
void insert (int n)
{
node *nn = new node;
nn->name = j++;
nn->tm = n;
nn->rt = nn->tm;
if (Head == NULL)
{
Head = nn;
Head->next = Head;
}
else
{
node *temp = Head;
while (temp->next != Head)
temp = temp->next;
nn->next = temp->next;
temp->next = nn;
}
}
void quantum (int t)
{
node *temp = Head;
int c = 0, i = 0;
while (Head != NULL)
{
{
temp->rt = temp->rt - t;
c = c + t;
if (temp->rt <= 0)
{
c = c + temp->rt;
cout << temp->name;
cout << c << endl;
del (temp->name);
if (temp->next == temp)
{
break;
}
}
temp = temp->next;
}
}
}
void del (char x)
{
node *p = NULL;
node *temp = Head;
if (Head->name == x)
{
while (temp->next != Head)
temp = temp->next;
p = Head;
temp->next = Head->next;
Head = Head->next;
delete p;
}
else
{
while (temp->name != x)
{
p = temp;
temp = temp->next;
}
p->next = temp->next;
delete temp;
}
}
};
int
main ()
{
rr robin;
int i, n, x, y, t;
cin >> y;
cin >> t;
for (i = 0; i < y; i++)
{
cin >> n;
robin.insert (n);
}
robin.quantum (t);
return 0;
}

Fail assertion opencv mat.inl.hpp line 930

I have a trivial problem but I don't know how to solve it. I just wanna do a simple "foreach" of a Mat to view rgb values. I have next code:
for(int i=0; i<mat.rows; i++)
{
for(int j=0; j<mat.cols; j++)
{
int value_rgb = mat.at<uchar>(i,j);
cout << "(" << i << "," << j << ") : " << value_rgb <<endl;
}
}
The mat is 200 rows x 200 cols. When I print on console the results, just in the final the programs fails with next error:
**OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 <(unsigned)size.p[0] && (unsigned)(i1*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channels()) && ((((sizeof(size_t)<<28)|0x8442211) >> ((DataType<_Tp>::depth) & ((1 << 3) - 1))*4) & 1 5) == elemSize1()) in unknown function, file c:\opencv\build\include\opencv2\core\mat.hpp, line 537**
Anyone can help me?
Thanks.
The below piece of code will help you in accessing the rgb pixel values.You have to access three channels to view RGB values.
for(int i = 0; i < i<mat.rows; i++)
{
for(int j = 0; j < mat.cols; j++)
{
int b = mat.at<cv::Vec3b>(i,j)[0];
int g = mat.at<cv::Vec3b>(i,j)[1];
int r = mat.at<cv::Vec3b>(i,j)[2];
cout << r << " " << g << " " << b << value_rgb <<endl ;
}
}
To read pixel value from a grayscale image
#include <opencv\cv.h>
#include <highgui\highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
cv::Mat img = cv::imread("5.jpg",0);
for(int j=0;j<img.rows;j++)
{
for (int i=0;i<img.cols;i++)
{
int a;
a=img.at<uchar>(j,i);
cout<<a<<endl;
}
}
cv::imshow("After",img);
waitKey(0);
}
Updated
This code reads all the grayscale values from an image and results in frequent occurring vales (Number of times the value as occurred). i.e
Number of times pixel value '0' as appeared,
Number of times pixel value '1' as appeared, ... & so on till 256.
#include <opencv\cv.h>
#include <highgui\highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
cv::Mat img = cv::imread("5.jpg",0);
//for(int j=0;j<img.rows;j++)
//{
// for (int i=0;i<img.cols;i++)
// {
// int a;
// a=img.at<uchar>(j,i);
// cout<<a<<endl;
// }
//}
vector<int> values_rgb;
for(int i=0; i<20; i++)
{
for(int j=0; j<20; j++)
{
int value_rgb = img.at<uchar>(i,j);
values_rgb.push_back(value_rgb);
//cout << "(" << i << "," << j << ") : " << value_rgb <<endl;
}
}
// Sorting of values in ascending order
vector<int> counter_rg_values;
for(int l=0; l<256; l++)
{
for(int k=0; k<values_rgb.size(); k++)
{
if(values_rgb.at(k) == l)
{
counter_rg_values.push_back(l);
}
}
}
//for(int m=0;m<counter_rg_values.size();m++)
//cout<<m<<" "<< counter_rg_values[m] <<endl;
int m=0;
for(int n=0;n<256;n++)
{
int c=0;
for(int q=0;q<counter_rg_values.size();q++)
{
if(n==counter_rg_values[q])
{
//int c;
c++;
m++;
}
}
cout<<n<<"= "<< c<<endl;
}
cout<<"Total number of elements "<< m<<endl;
cv::imshow("After",img);
waitKey(0);
}

getting primal form from CvSVM trained file

I am trying to train my own detector based on HOG features and i trained a detector with CvSVM utility of opencv. Now to use this detector in HOGDescriptor.SetSVM(myDetector), i need to get trained detector in row-vector (primal) form to feed. For this i am using this code. my implementation is like given below:
vector<float>primal;
void LinearSVM::getSupportVector(std::vector<float>& support_vector) {
CvSVM svm;
svm.load("Classifier.xml");
cin.get();
int sv_count = svm.get_support_vector_count();
const CvSVMDecisionFunc* df = decision_func;
const double* alphas = df[0].alpha;
double rho = df[0].rho;
int var_count = svm.get_var_count();
support_vector.resize(var_count, 0);
for (unsigned int r = 0; r < (unsigned)sv_count; r++) {
float myalpha = alphas[r];
const float* v = svm.get_support_vector(r);
for (int j = 0; j < var_count; j++,v++) {
support_vector[j] += (-myalpha) * (*v);
}
}
support_vector.push_back(rho);
}
int main()
{
LinearSVM s;
s.getSupportVector(primal);
return 0;
}
When i use built-in CvSVM, it shows me SV as 3 bec i have only 3 SV in my saved file but since the decision_func is in protected mode, hence i can not access it. That's why i tried to use that wrapper but still of no use. Perhaps you guys can help me out here... Thanks alot!
Answer with a test harness. I put in new answer as it would add allot of clutter to the original answer, possibly making it a bit confusing.
//dummy features
std:: vector<float>
dummyDerReaderForOneDer(const vector<float> &pattern)
{
int i = std::rand() % pattern.size();
int j = std::rand() % pattern.size();
vector<float> patternPulNoise(pattern);
std::random_shuffle(patternPulNoise.begin()+std::min(i,j),patternPulNoise.begin()+std::max(i,j));
return patternPulNoise;
};
//extend CvSVM to get access to weights
class mySVM : public CvSVM
{
public:
vector<float>
getWeightVector(const int descriptorSize);
};
//get the weights
vector<float>
mySVM::getWeightVector(const int descriptorSize)
{
vector<float> svmWeightsVec(descriptorSize+1);
int numSupportVectors = get_support_vector_count();
//this is protected, but can access due to inheritance rules
const CvSVMDecisionFunc *dec = CvSVM::decision_func;
const float *supportVector;
float* svmWeight = &svmWeightsVec[0];
for (int i = 0; i < numSupportVectors; ++i)
{
float alpha = *(dec[0].alpha + i);
supportVector = get_support_vector(i);
for(int j=0;j<descriptorSize;j++)
{
*(svmWeight + j) += alpha * *(supportVector+j);
}
}
*(svmWeight + descriptorSize) = - dec[0].rho;
return svmWeightsVec;
}
// main harness entry point for detector test
int main (int argc, const char * argv[])
{
//dummy variables for example
int posFiles = 10;
int negFiles = 10;
int dims = 1000;
int randomFactor = 4;
//setup some dummy data
vector<float> dummyPosPattern;
dummyPosPattern.assign(int(dims/randomFactor),1.f);
dummyPosPattern.resize(dims );
random_shuffle(dummyPosPattern.begin(),dummyPosPattern.end());
vector<float> dummyNegPattern;
dummyNegPattern.assign(int(dims/randomFactor),1.f);
dummyNegPattern.resize(dims );
random_shuffle(dummyNegPattern.begin(),dummyNegPattern.end());
// the labels and lables mat
float posLabel = 1.f;
float negLabel = 2.f;
cv::Mat cSvmLabels;
//the data mat
cv::Mat cSvmTrainingData;
//dummy linear svm parmas
SVMParams cSvmParams;
cSvmParams.svm_type = cv::SVM::C_SVC;
cSvmParams.C = 0.0100;
cSvmParams.kernel_type = cv::SVM::LINEAR;
cSvmParams.term_crit = cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 1000000, FLT_EPSILON);
cout << "creating training data. please wait" << endl;
int i;
for(i=0;i<posFiles;i++)
{
//your feature for one box from file
vector<float> d = dummyDerReaderForOneDer(dummyPosPattern);
//push back a new mat made from the vectors data, with copy data flag on
//this shows the format of the mat for a single example, (1 (row) X dims(col) ), as training mat has each **row** as an example;
//the push_back works like vector add adds each example to the bottom of the matrix
cSvmTrainingData.push_back(cv::Mat(1,dims,CV_32FC1,d.data(),true));
//push back a pos label to the labels mat
cSvmLabels.push_back(posLabel);
}
//do same with neg files;
for(i=0;i<negFiles;i++)
{
float a = rand();
vector<float> d = dummyDerReaderForOneDer(dummyNegPattern);
cSvmTrainingData.push_back(cv::Mat(1,dims,CV_32FC1,d.data(),true));
cSvmLabels.push_back(negLabel);
}
//have a look
cv::Mat viz;
cSvmTrainingData.convertTo(viz,CV_8UC3);
viz = viz*255;
cv::imshow("svmData", viz);
cv::waitKey(10);
cout << "press any key to continue" << endl;
getchar();
viz.release();
//create the svm;
cout << "training, please wait" << endl;
mySVM svm;
svm.train(cSvmTrainingData,cSvmLabels,cv::Mat(),cv::Mat(),cSvmParams);
cout << "get weights" << endl;
vector<float> svmWeights = svm.getWeightVector(dims);
for(i=0; i<dims+1; i++)
{
cout << svmWeights[i] << ", ";
if(i==dims)
{
cout << endl << "bias: " << svmWeights[i] << endl;
}
}
cout << "press any key to continue" << endl;
getchar();
cout << "testing, please wait" << endl;
//test the svm with a large amount of new unseen fake one at a time
int totExamples = 10;
int k;
for(i=0;i<totExamples; i++)
{
cout << endl << endl;
vector<float> dPos = dummyDerReaderForOneDer(dummyPosPattern);
cv::Mat dMatPos(1,dims,CV_32FC1,dPos.data(),true);
float predScoreFromDual = svm.predict(dMatPos,true);
float predScoreBFromPrimal = svmWeights[dims];
for( k = 0; k <= dims - 4; k += 4 )
predScoreBFromPrimal += dPos[k]*svmWeights[k] + dPos[k+1]*svmWeights[k+1] +
dPos[k+2]*svmWeights[k+2] + dPos[k+3]*svmWeights[k+3];
for( ; k < dims; k++ )
predScoreBFromPrimal += dPos[k]*svmWeights[k];
cout << "Dual Score:\t" << predScoreFromDual << "\tPrimal Score:\t" << predScoreBFromPrimal << endl;
}
cout << "press any key to continue" << endl;
getchar();
return(0);
}
Hello again :) please extend the cvsm class rather than encapsulating it, as you need access to protected member.
//header
class mySVM : public CvSVM
{
public:
vector<float>
getWeightVector(const int descriptorSize);
};
//cpp
vector<float>
mySVM::getWeightVector(const int descriptorSize)
{
vector<float> svmWeightsVec(descriptorSize+1);
int numSupportVectors = get_support_vector_count();
//this is protected, but can access due to inheritance rules
const CvSVMDecisionFunc *dec = CvSVM::decision_func;
const float *supportVector;
float* svmWeight = &svmWeightsVec[0];
for (int i = 0; i < numSupportVectors; ++i)
{
float alpha = *(dec[0].alpha + i);
supportVector = get_support_vector(i);
for(int j=0;j<descriptorSize;j++)
{
*(svmWeight + j) += alpha * *(supportVector+j);
}
}
*(svmWeight + descriptorSize) = - dec[0].rho;
return svmWeightsVec;
}
something like that.
credits:
Obtaining weights in CvSVM, the SVM implementation of OpenCV

Resources