Why is this vector not populating with values? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 13 days ago.
This post was edited and submitted for review 13 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
This function is intended to take a vector with x,y value pairs of the form {x1, x2, x3, y1, y2, y3} and return a vector with the values shuffled as such {x1, y1, x2, y2, x3, y3}. The size of the vector is 2*n, where n is the number of x values/y values respectively. By using print statements inside the function, I've already determined that the algorithm works.
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> temp;
temp.reserve(2*n);
int xCounter = 0;
int yCounter = n;
for (int i=0; i<2*n; i+=2){
// populate arr x val
temp[i] = (nums[xCounter]);
// populate arr y val
temp[i+1] = (nums[yCounter]);
++xCounter;
++yCounter;
}
return temp;
}
int main()
{
vector<int> yoMomma = {1,2,3,1,2,3};
vector<int> ans;
ans = shuffle(yoMomma,yoMomma.size()/2);
return 0;
}

You called reserve, not resize, so your vector isn't actually increased in size, just capacity (pre-allocated memory that can hold elements in the future without having to reallocate). But that makes all your indexing assignments illegal; the vector still has a length of 0, you can't assign to any index. It happens to work because the reserve ensures there is memory there, but said memory would never be properly destructed (so it's a good thing you're using primitive types without destructors).
Change your loop to:
for (int i=0; i<n; ++i){
// populate arr x val
temp.push_back(nums[i]);
// populate arr y val
temp.push_back(nums[i+n]);
}
pushing new values onto the end, and saving a couple unnecessary variables, rather than indexing.

Related

Using memcpy to copy a range of elements from an 2d array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Say we have two 2d arrays:
double matrix [64][100];
double array[64][32];
And we want to copy 32 elements from matrix[64][50:82] to array[64][32] using memcpy.
Do you the solution?
double matrix[64][100];
double array[64][32];
for (int i = 0; i < 64; ++i) {
memcpy(&array[i][0], &matrix[i][50], sizeof(double) * 32);
}
However, consider using std::copy() or std::copy_n() instead. They will use memcpy() internally when safe to do so:
#include <algorithm>
double matrix[64][100];
double array[64][32];
for (int i = 0; i < 64; ++i) {
std::copy(&matrix[i][50], &matrix[i][82], &array[i][0]);
or
std::copy_n(&matrix[i][50], 32, &array[i][0]);
}

for loop counter doesn't increment [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
i'm having some issues with this bit of code. basically "k" doesn't increment more than 1. I've already tried to declare it outside the loop but doesn't fix it. basically what the code does is generating a grid of crystals.
this is a uni assessment and at the moment I'am a newbie with console functions, especially managing the cursor. as you can see, at every iteration i add +2 to pos.x. it seems to work, but when it starts again, pos.x returns to the start value and instead is pos.y to increment(?).
void gridGeneration(Crystal simbols[][Columns])
{
COORD pos = {10, 55};
for (int i = 0; i < Rows; i++)
for (int k = 0; k < Columns; k++)
{
WriteCrystalAt(simbols[i][k].crystal, pos.X, pos.Y, simbols[i][k].color= rand() % light_yellow + light_blue);
pos.X += 2;
if (k = 1)
{
pos.X = 10;
pos.Y += 2;
}
}
}
It would increment further than 1, but you keep setting it to 1 again:
if (k = 1)
You should use == for comparisons.
Your compiler should have issued a warning about this. If it did not, review your warning settings. If it did, stop ignoring warnings.

A recursive puzzle c++ code [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
A recursive puzzle You have been given a puzzle consisting of a row of squares each containing an integer, like this
The circle on the initial square is a marker that can move to other squares along the row. At each step in the puzzle, you may move the marker the number of squares indicated by the integer in the square it currently occupies. The marker may move either left or right along the row but may not move past either end. For example, the only legal first move is to move the marker three squares to the right because there is no room to move three spaces to the left. The goal of the puzzle is to move the marker to the 0 at the far end of the row. In this configuration, you can solve the puzzle by making the following set of moves:
https://i.stack.imgur.com/yUz3P.png
a. Write an algorithm void SolvePuzzle(int start, int squares[1..n]) that takes a starting position of the marker along with the array of squares. The algorithm should solve the puzzle from the starting configuration and display all moves required to reach the 0 at the end of the sequence. You may assume all the integers in the array are positive except for the last entry, the goal square, which is always zero. The values of the elements in the array must be the same after calling your function as they are beforehand, (which is to say if you change them during processing, you need to change them back!)
void SolvePuzzle(int start, int squares[]){
if(squares[start]==0)
return;
else{
cout<<squares[start]<<" ";
if(squares[start]%2==0)
SolvePuzzle( start+squares[start],squares);
else
SolvePuzzle( start-squares[start],squares);
}
}
int main(){
int arraytest[] = { 3, 6, 4, 1, 3, 4, 2, 5, 3, 0 };
SolvePuzzle(arraytest[0],arraytest);
return 0;
}
i solved like this but i need Correct mistakes in If statement
The problem you are facing, even if one could not really tell from your description, is that you don't really know if you have to move left or right to solve the puzzle.
The simplest approach is just try to go left, if it works you solved it, otherwise you go right. This means that you have to change your function, otherwise you cannot really return the right path or the answer.
It may appear like this:
#include <vector>
#include <iostream>
bool SolvePuzzle(int squares[], int size, int position,
std::vector<bool>& go_right_sol){
if(squares[position]==0){
return true;
}
int leftPos = position - squares[position];
int rightPos = position + squares[position];
if(rightPos < size && SolvePuzzle(squares, size, rightPos, go_right_sol)){
go_right_sol.insert(go_right_sol.begin(), true);
return true;
}
if(leftPos > 0 && SolvePuzzle(squares, size, leftPos, go_right_sol)){
go_right_sol.insert(go_right_sol.begin(), false);
return true;
}
return false;
}
int main(){
int arraytest[] = { 3, 6, 4, 1, 3, 4, 2, 5, 3, 0 };
int arraysize = 10;
std::vector<bool> solution;
SolvePuzzle(arraytest, arraysize, 0, solution);
for(int i = 0; i < solution.size(); i++){
std::cout << ((solution[i]) ? "right" : "left") << " - ";
}
std::cout << std::endl;
return 0;
}

c++, boost, store objects in multidimensional array without default constructor

I want to store thousands of interpolation functions in a multidimensional array, preferable the one from boost. The main problem is that the interpolation function I use is a class that does not have a default constructor. This prohibits me to initialize the multidimensional array.
What I wish I could do:
double func(const double& x1, const double& x2, const double& x3)
{
return x1 + x2 + x3;
};
int main()
{
std::vector<double> x1 {0, 1, 2, 3};
std::vector<double> x2 {1.1, 1.2, 1.3, 1.4, 1.5};
std::vector<double> x3 {0, 10, 20, 30, 40};
std::vector<double> y(20, std::vector<double>(5));
boost::multi_array<Linear_interp, 2> Storage(boost::extents[4][5]);
typedef std::vector<double>::size_type vd_sz;
int n = 0;
for (vd_sz i_x1 = 0; i_x1 < x1.size(); ++i_x1) {
for (vd_sz i_x2 = 0; i_x2 < x2.size(); ++i_x2) {
for( vd_sz i_x3 = 0; i_x3 < x3.size(); ++i_x3) {
y[n][i_x3] = func(x1[i_x1], x2[i_x2], x3[i_x3]);
}
Linear_interp myInterp(x3, y);
Storage[i_x1][i_x2] = myInterp;
++n;
}
}
// Sample usage
double z = Storage[3][2].interp(23);
return 0;
}
The problem is that the class Linear_interp has no default constructor (the class is similar to this class 1), therefore boost::multi_array can not initialize the array.
Note that I initialize all interpolations inside a loop and therefore, I need to store these objects. A simple pointer to the object will not work, since the object will be overwritten in each loop.
In reality, I will have much more dimensions (atm I have 10), and multi_array is a nice container to handle these. Additionally, Interpolations in later loops, will take interpolations from previous loops (i.e. I have a recursive problem).
EDIT 1: Minor code correction.
EDIT 2: code correction: in the previous version, i did not save the "y"s which lead to unwanted results.
Well pointer WILL work. If you will declare your array as:
multi_array<Linear_interp*, 2>
to store pointers to the the objects instead of objects themselves.
Then in the loop you could allocate new object each time it would be necessary and put it to the appropriate place in the array. Just use new keyword to create new Linear_interp object inside the loop. Here is code to use inside the loop:
Storage[i_x1][i_x2] = new Linear_interp(x3, y);
I'm not a boost expert, but I'm sure there is an equivalent solution. You could do the following steps:
Make sure to build a complete "matrix" with empty innermost arrays. Something like the following (using std::vector) works for 3 dimensions:
std::vector<std::vector<std::vector<Linear_interp>>> Storage;
Storage.resize(x1.size());
for (vd_sz i_x1 = 0; i_x1 < x1.size(); i_x1++) {
Storage[i_x1].resize(x2.size());
}
At this point, Storage[i][j] is an existing, but empty std::vector<Linear_interp>. So now you can use std::vector::emplace_back or (::push_back with C++11) to fill your Storage. Going back to two dimensions and your original code, something like this will do the job:
typedef std::vector<double>::size_type vd_sz;
for (vd_sz i_x1 = 0; i_x1 < x1.size(); i_x1++) {
for (vd_sz i_x2 = 0; i_x2 < x2.size(); i_x2++) {
for( vd_sz i_x3 = 0; i_x3 < x3.size(); i_x3++) {
y[i_x3] = func(x1[i_x1], x2[i_x2], x3[i_x3]);
}
Storage[i_x1][i_x2].emplace_back(x3, y);
// or: Storage[i_x1][i_x2].push_back(Linear_interp(x3, y));
}
}
Using push_back or similar methods, will only call a copy c'tor and hence work for your non-default-constructible type Linear_interp.

Generating random reals uniformly using Boost [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to generate some uniform real numbers for a Monte Carlo integration but the routine I build was returning some really strange values. Upon closer inspection I notices that Boost was returning some crazy looking random numbers e.g.:
temp = -0.185276
temp = -0.864523
temp = -0.0942081
temp = -0.164991
temp = -0.873013
temp = -0.0311322
temp = -0.0866241
temp = -0.778966
temp = -0.367641
temp = -0.691833
temp = 5.66499e-310
temp = 9.42007e-311
temp = 6.29821e-310
temp = 5.80603e-310
temp = 8.82973e-311
temp = 6.73679e-310
temp = 6.35094e-310
temp = 1.53691e-310
temp = 4.39696e-310
temp = 2.14277e-310
Whilst these numbers are technically still reals generated between the bounds -1 and 1 I would prefer it if they weren't quite so small!
My implementation of the call to boost is in a function which is called multiple times (for different bounding values) as follows:
// Define Boost typedefs
typedef boost::mt19937 Engine;
typedef boost::uniform_real<double> Distribution;
typedef boost::variate_generator <Engine, Distribution> Generator;
int main (void) {
...
Integral = MCRecursion(...);
...
return 0;
}
double MCRecursion (int Count, double Lower, double Upper, double (*Integrand)(double)) {
// Define Boost objects
Engine Eng;
Distribution Dist (Lower, Upper);
Generator RandomGen (Eng, Dist);
Eng.seed(time(0));
// Variables for Monte Carlo sample sums
double Sum = 0.0;
double temp;
for (int i = 0; i < Count; i++) {
temp = RandomGen();
std::cout << " temp = " << temp << std::endl;
Sum += Integrand(temp);
}
return (Upper - Lower) * Sum / Count;
}
I assume the problem is something with my implementation but I can't find any errors. Any and all help appreciated!
Cheers,
Jack
EDIT
Code for calling MCRecursion:
The Code I am writting runs a Monte Carlo on the entire domain I am interested in [Lower, Upper] and then looks again at the left half of the whole domain and the right half of the domain.
e.g. if we were integrating f(x) between -a and a I calculate the full integral using:
double FullDomain = MCRecursion (1e5, LowerBound, UpperBound, f);
double Centre = (Upper + Lower) / 2.0;
double LeftHalf = MCRecursion (1e5, LowerBound, Centre, f);
double RightHalf = MCRecursion (1e5, Centre, UpperBound, f);
and I then look at the uncertainty by calculating:
double difference = fabs(FullDomain - LeftHalf - Righthalf);
to see if more samples is 'worth it' in some sense
Jack
Based on the pastebin the questioner posted in the comments:
This is not a problem with the random library but rather a simple programming error. Compiling the code throws the warning:
../src/Test.cpp: In function ‘double AdaptiveMCRecursion(double, double, double, double, int, double, double (*)(double))’:
../src/Test.cpp:100:72: warning: ‘Right’ is used uninitialized in this function [-Wuninitialized]
double Right = MCSample (Count, Central, Right, Integrand);
So all the behaviour from that line on is basically undefined. Especially it results in calling the function MCSample with an undetermined Upper parameter. So your result is not unexpected. You are actually lucky the program runs at all.