problrm with array in c++ - c++

this is my Stata.h
#include "State.h"
#include <iostream>
using namespace std;
class State
{
public:
int data[4][4];
int x;
int y;
int cost[];
State(void);
void CopyState(State*);
bool equals(State*);
int h(State*);
void print(void);
private:
int getLocation(State, int, int);
};
and this is my State.cpp
#include "State.h"
#include <iostream>
using namespace std;
State::State(void)
{
State::cost[] = {0, 3, 2, 5, 3, 4, 1, 2, 2, 1, 4, 3,
5, 2, 3, 2, 3, 0, 3, 2, 2, 3, 2, 1,
1, 2, 1, 4, 2, 3, 2, 3, 2, 3, 0, 3,
1, 2, 3, 2, 4, 1, 2, 1, 3, 2, 3, 2,
5, 2, 3 ,0 ,2 , 1 , 4 , 3 ,3 , 4 ,1 , 2,
2, 3, 2, 5, 3, 2, 1, 2, 0, 3, 2, 3,
3, 2, 1 ,2 ,2 , 1 ,4 ,3 , 4 ,3 ,2 , 1 ,
3 ,0, 3, 2, 2 , 3, 2, 1 , 1 , 2, 1, 4,
1 , 2, 3 ,4 ,2 ,3 ,0 ,3 ,1 , 2 ,3 ,2 ,
4 ,1, 2, 1, 2, 1, 2, 3, 3, 2, 3, 0,
2 ,1, 2 , 3 ,3 ,4 ,1 ,2 , 2 , 1 ,4 ,3,
3 , 2, 1, 2, 0 , 3 , 2 , 3, 3 , 2, 1, 2,
1 ,2, 1 , 4 ,2 ,3 ,2 , 1 , 3 , 0 , 3 , 2,
4 , 3, 2 , 1 , 4 , 1, 2 , 1 , 1 , 2, 3 , 2,
2, 3 ,0 ,3 ,1 , 2 , 3 , 4 , 3 ,4 , 1 ,2,
2 ,1, 2, 3 , 3 , 2 , 3 , 0, 2, 1, 2, 3,
5 , 2 ,3 , 2 ,2 ,1 , 4 ,3 ,3 ,4 ,1 ,2,
0 ,3, 2, 5, 2 , 3 , 2, 3, 1, 2, 1, 4,
2 ,3 ,2 , 1 ,3 , 0 ,3 , 2, 3 , 2 ,3 ,2 ,
4 ,1, 2, 1, 1 , 2, 3 , 2 , 2, 3 , 0, 3,
2 ,3 ,2 , 5 , 3 , 4 , 1 , 2 , 2 , 1 ,4 , 3 ,
5 , 2 ,3 ,0
};
}
void State::CopyState(State *state)
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
data[i][j] = state->data[i][j];
x = state->x;
y = state->y;
}
bool State::equals(State *state)
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if (data[i][j] != state->data[i][j])
return false;
return true;
}
int State::h(State *state)
{
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
int frmPos = 4 * i + j;
int toPos = getLocation(*state, i, j);
k += cost[16 * frmPos + toPos];
}
return k;
}
void State::print()
{
cout << "\n";
for (int i = 0; i < 4; i++)
{
cout << "\n";
for (int j = 0; j < 4; j++)
cout << data[i][j];
}
cout << endl;
}
the problem is in State.cpp in the constructor when I'm trying to assign values to the cost array I don't know where is the problem, please any one can solve that , sorry for my bad english

You can't do it that way. There's a couple of problems, but the first problem is this:
In the header you declare cost as an array with an unspecified size:
int cost[];
This isn't allowed in Standard C++ because now the compiler doesn't know how big the array is, and therefore doesn't know how big State will be. (Some compilers do allow it, but it's a special extension that won't work on other compilers.)
The simplest and often best way to do this is to use a vector:
#include <vector>
class State
{
// ...
std::vector <int> cost;
};
And then in the constructor:
State::State()
{
static const int startingValues [] =
{0, 3, 2, 5, 3, 4, 1, 2, 2, 1, 4, 3, ... };
static const size_t numStartingValues = sizeof (startingValues) / sizeof (startingValues [0]);
std::copy (startingValues, startingValues + numStartingValues, std::back_inserter (cost));
}
If you're using C++11, then this is made simpler with the uniform initialization syntax:
State::State()
:
cost {0, 3, 2, 5, ...}
{
}

First of all, the cost member is not an array, it is a pointer (or it was when I looked at it, but you've changed it. However, it's still not an array. It is now a compiler error.). If you want it to point to an array, first you have to allocate it. But that's a terrible idea. Change it to a vector:
class State {
...
std::vector<int> cost;
...
};
Then, in your constructor, you can initialize it like this (if your compiler supports C++11)
State::State() :
cost{0, 3, 2, 5, 3, 4} // trimmed for brevity, but you can put as many elements as you want
{}
If your compiler does not support C++11 (or does not support this feature), then you can initialize the vector like this:
State::State()
{
static int temp[] = {0, 3, 2, 5, 3, 4};
cost.assign(temp, temp + sizeof(temp) / sizeof(*temp));
}

Related

How to remove duplicates in particular set of data?

Let's suppose we have two childs who want to get same number or coins (coin nominals 1,2,6,12). Childs don't care about the value.
Example container of permutations which I want to share between two childs:
{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}
Now I`d like to have collections without duplicates:
child A child B
2 2 1 1
2 1 2 1
1 1 2 2
1 1 1 1 1 1
That permutations are wrong:
1 2 1 2
1 2 2 1
2 1 1 2
because
child A child B
1 2 1 2
is permutation of
child A child B
2 1 2 1
which we already have. These collections: 1 2 2 1 and 2 1 1 2 are permutations, as well.
My solution is here, works correctly for that particular input but if you add more coins with different nominals, it doesn't!
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int main()
{
vector<vector<int>> permutations =
{
{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}
};
vector<pair<unordered_multiset<int>, unordered_multiset<int>>> childSubsets;
for(const auto &currentPermutation : permutations)
{
size_t currentPermutationSize = currentPermutation.size();
size_t currentPermutationHalfSize = currentPermutationSize / 2;
//left
unordered_multiset<int> leftSet;
for(int i=0;i<currentPermutationHalfSize;++i)
leftSet.insert(currentPermutation[i]);
bool leftSubsetExist = false;
for(const auto &subset : childSubsets)
{
if(subset.first == leftSet)
{
leftSubsetExist = true;
break;
}
}
//right
unordered_multiset<int> rightSet;
for(int i = currentPermutationHalfSize; i < currentPermutationSize; ++i)
rightSet.insert(currentPermutation[i]);
bool rightSubsetExist = false;
for(const auto &subset : childSubsets)
{
if(subset.second == rightSet)
{
rightSubsetExist = true;
break;
}
}
//summarize
if(!leftSubsetExist || !rightSubsetExist) childSubsets.push_back({leftSet, rightSet});
}
cout << childSubsets.size() << endl;
}
How to change the solution to make optimal and less complex?
You should add
if (leftSubsetExist)
continue;
after first cycle (as optimization)
Could you add some "wrong" permutations (with another coins)?

Cannot specify explicit initializer for arrays [SystemC]

Im using VS2013 along with the SystemC library from Allegro. I was trying to initialize two arrays as follows:
int pathObs1[19] = {10,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,10};
int Map[10][4] = {
{ 0, 3, 1, 4 }, //Grid 1
{ 1, 3, 2, 4 }, //Grid 2
{ 2, 3, 3, 4 }, //Grid 3
{ 3, 3, 4, 4 }, //Grid 4
{ 4, 3, 5, 4 }, //Grid 5
{ 5, 3, 6, 4 }, //Grid 6
{ 6, 3, 7, 4 }, //Grid 7
{ 6, 2, 7, 3 }, //Grid 8
{ 6, 1, 7, 2 }, //Grid 9
{ 6, 0, 7, 1 } //Grid 10
};
However i received the error the above error. I saw some questions on SO which had the same issue, however I dont think they were dealing with SystemC. Any easy workaround for this in SystemC since im trying to initialize inside my SC_MODULE header/constructor?
Edit: I had a typo in my array initialization. Still get the same error.
2dArray[m][n] means m rows n columns so you can keep n values in each row but in your code you defined matrix which had 3 columns but still you are assigning 4 values.
You can use a loop for filling the array:
#include <iostream>
#include <stdlib>
int main()
{
srand(time(null));
int map[10][4];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 4; j++)
{
map[i][j] = rand(); // you can write smth like rand() % 5 to make a limit of the values
}
}
return 0;
}

Max subarray with start and end index

I'm trying to find the maximum contiguous subarray with start and end index. The method I've adopted is divide-and-conquer, with O(nlogn) time complexity.
I have tested with several test cases, and the start and end index always work correctly. However, I found that if the array contains an odd-numbered of elements, the maximum sum is sometimes correct, sometimes incorrect(seemingly random). But for even cases, it is always correct. Here is my code:
int maxSubSeq(int A[], int n, int &s, int &e)
{
// s and e stands for start and end index respectively,
// and both are passed by reference
if(n == 1){
return A[0];
}
int sum = 0;
int midIndex = n / 2;
int maxLeftIndex = midIndex - 1;
int maxRightIndex = midIndex;
int leftMaxSubSeq = A[maxLeftIndex];
int rightMaxSubSeq = A[maxRightIndex];
int left = maxSubSeq(A, midIndex, s, e);
int right = maxSubSeq(A + midIndex, n - midIndex, s, e);
for(int i = midIndex - 1; i >= 0; i--){
sum += A[i];
if(sum > leftMaxSubSeq){
leftMaxSubSeq = sum;
s = i;
}
}
sum = 0;
for(int i = midIndex; i < n; i++){
sum += A[i];
if(sum > rightMaxSubSeq){
rightMaxSubSeq = sum;
e = i;
}
}
return max(max(leftMaxSubSeq + rightMaxSubSeq, left),right);
}
Below is two of the test cases I was working with, one has odd-numbered elements, one has even-numbered elements.
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
Edit: The following are the 2 kinds of outputs:
// TEST 1
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 32769 // Index is correct, but sum should be 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39 // correct
// TEST 2
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39
Can anyone point out why this is occurring? Thanks in advance!
Assuming that n is the correct size of your array (we see it being passed in as a parameter and later used to initialize midIndexbut we do not see its actual invocation and so must assume you're doing it correctly), the issue lies here:
int midIndex = n / 2;
In the case that your array has an odd number of elements, which we can represented as
n = 2k + 1
we can find that your middle index will always equate to
(2k + 1) / 2 = k + (1/2)
which means that for every integer, k, you'll always have half of an integer number added to k.
C++ doesn't round integers that receive floating-point numbers; it truncates. So while you'd expect k + 0.5 to round to k+1, you actually get k after truncation.
This means that, for example, when your array size is 11, midIndex is defined to be 5. Therefore, you need to adjust your code accordingly.

storing a 2D array into a 2D vector in c++

Suppose I have a following 2D matrix in the following format. First line indicates the dimension and the rest other lines contains the elements. In this case it's a 6*6 Matrix:
6
1 2 3 4 2 3
3 3 4 5 2 1
4 3 3 1 2 3
5 4 3 6 2 1
3 2 4 3 4 3
2 3 4 1 5 6
Normally we can store the matrix in a vector using this:
typedef std::vector<int32_t> vec_1d;
typedef std::vector<vec_1d> vec_2d;
vec_2d array{
{ 1, 2, 3, 4, 2, 3 }
, { 3, 3, 4, 5, 2, 1 }
, { 4, 3, 3, 1, 2, 3 }
, { 5, 4, 3, 6, 2, 1 }
, { 3, 2, 4, 3, 4, 3 }
, { 2, 3, 4, 1, 5, 6 }
};
But if I want to take this array in the format I have shown above from a text file into a 2d vector like the above one, how will I do this in c++ ?
This should work:
#include "fstream"
#include "vector"
using namespace std;
int main()
{
ifstream fin("file.txt");
int n;
fin >> n;
vector < vector <int> > matrix (n, vector <int>(n));
// or vec_2d matrix (n, vec_1d(n)); with your typedefs
for (auto &i: matrix)
for (auto &j: i)
fin >> j;
}

Extracting and sorting data in an array?

Here is my array:
int grid[gridsize+1] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6, 4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8, 4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8 };
Each number represents a colour, I would like to create multiple arrays for each unique number. The created arrays will store the locations of that number from the original array.
e.g
colour1[5]
[0]=0 //because the number 1 is stored in element 0.
[1]=1
[2]=8
[3]=9
The numbers in grid will change every time I run, so things need to be dynamic?
I can write inefficient code that accomplishes this, but it's just repetitive and I can't comprehend a way to turn this into something I can put in a function.
Here is what I have;
int target_number = 1
grid_size = 64;
int counter = -1;
int counter_2 = -1;
int colour_1;
while (counter < grid_size + 1){
counter = counter + 1;
if (grid[counter] == target)
counter_2 = counter_2 + 1;
colour_1[counter_2] = counter;
}
}
I have to do this for each colour, when I try to make a function, it cannot access the main array in main so is useless.
You can just use vector<vector<int>> to represent your counters. No maps or sorting are needed.
EDIT: added additional pass to determine maximum color, so no run-time resize is needed.
Here is the code:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int grid[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, /*...*/};
const size_t gridSize = std::end(grid) - std::begin(grid);
int maxColor = *std::max_element(std::begin(grid), std::end(grid));
std::vector<std::vector<int>> colorPos(maxColor);
for (size_t i = 0; i < gridSize; ++i)
colorPos[grid[i] - 1].push_back(i);
for (size_t i = 0; i < colorPos.size(); ++i) {
std::cout << (i + 1) << ": ";
for (int p : colorPos[i])
std::cout << p << ' ';
std::cout << std::endl;
}
return 0;
}
The output:
1: 0 1 8 9 10 17
2: 2 3 4 5 6 7 14 15 22 30
3: 11 12 13 19 20 28
4: 16 24 32 33 40 48 56
5: 18 25 26 27 34 35 36 44
6: 21 23 29 31 37 38 39
7: 41 42 49 50 57 58 59 60
8: 43 45 46 47 51 52 53 54 55 61 62 63
I think you'd be best off using a counting sort, which is a sorting algorithm that works very well for sorting large groups of simple types with many duplicate values in better than O(n log n) time. Here's some sample code, annotated for clarity:
// set up our grid
int grid_raw[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6, 4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8, 4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8};
// build a vector using our raw list of numbers. This calls the range constructor:
// (number 3) http://www.cplusplus.com/reference/vector/vector/vector/
// The trick to using sizeof is that I don't have to change anything if my grid's
// size changes (sizeof grid_raw gives the number of bytes in the whole array, and
// sizeof *grid_raw gives the number of bytes in one element, so dividing yields
// the number of elements.
std::vector<int> grid(grid_raw, grid_raw + sizeof grid_raw / sizeof *grid_raw);
// count the number of each color. std::map is an associative, key --> value
// container that's good for doing this even if you don't know how many colors
// you have, or what the possible values are. Think of the values in grid as being
// colors, not numbers, i.e. ++buckets[RED], ++buckets[GREEN], etc...
// if no bucket exists for a particular color yet, then it starts at zero (i.e,
// the first access of buckets[MAUVE] will be 0, but it remembers each increment)
std::map<int, int> buckets;
for (vector<int>::iterator i = grid.begin(); i != grid.end(); ++i)
++buckets[*i];
// build a new sorted vector from buckets, which now contains a count of the number
// of occurrences of each color. The list will be built in the order of elements
// in buckets, which will default to the numerical order of the colors (but can
// be customized if desired).
vector<int> sorted;
for (map<int, int>::iterator b = buckets.begin(); b != buckets.end(); ++b)
sorted.insert(sorted.end(), b->second, b->first);
// at this point, sorted = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, ...}
Read more about the Counting Sort (includes example python code)
Here's an ideone that demonstrates sorting your grid.
I'm not 100% sure this answers your question... but you included sorting in the title, even though you didn't say anything about it in the body of your question.
Maybe it would be better to use some associative container as for example std::unordered_map or std::multimap.
Here is a demonstrative program
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for ( int x : grid )
{
m.insert( { x, i++ } );
}
std::multimap<int, int>::size_type n = m.count( 1 );
std::cout << "There are " << n << " elements of color 1:";
auto p = m.equal_range( 1 );
for ( ; p.first != p.second ; ++p.first )
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
return 0;
}
The output
There are 6 elements of color 1: 0 1 8 9 10 17
Or
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for ( int x : grid )
{
m.insert( { x, i++ } );
}
for ( auto first = m.begin(); first != m.end(); )
{
auto n = m.count( first->first );
std::cout << "There are " << n
<< " elements of color " << first->first << ":";
auto p = m.equal_range( first->first );
for ( ; p.first != p.second ; ++p.first )
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
first = p.first;
}
return 0;
}
the output is
There are 6 elements of color 1: 0 1 8 9 10 17
There are 10 elements of color 2: 2 3 4 5 6 7 14 15 22 30
There are 6 elements of color 3: 11 12 13 19 20 28
There are 7 elements of color 4: 16 24 32 33 40 48 56
There are 8 elements of color 5: 18 25 26 27 34 35 36 44
There are 7 elements of color 6: 21 23 29 31 37 38 39
There are 8 elements of color 7: 41 42 49 50 57 58 59 60
There are 12 elements of color 8: 43 45 46 47 51 52 53 54 55 61 62 63
If you are not forced to use plain arrays, I can propose a map of colors to a vector of positions:
the map is an associative container, that for any color key returns a reference
the referenced used here will be a vector (a kind of dynamic array) containing all the positions.
Your input grid contains color codes:
typedef int colorcode; // For readability, to make diff between counts, offsets, and colorcodes
colorcode grid[] = { 1, 1, /* .....input data as above.... */ ,8 };
const size_t gridsize = sizeof(grid) / sizeof(int);
You would then define the color map:
map<colorcode, vector<int>> colormap;
// ^^^ key ^^^ value maintained for the key
With this approach, your color1[..] would then be replaced by a more dynamic corlormap[1][..]. And it's very easy to fill:
for (int i = 0; i < gridsize; i++)
colormap[grid[i]].push_back(i); // add the new position to the vector returned for the colormap of the color
To verify the result, you may iterate through the map, and for each existing value iterate through the positions:
for (auto x : colormap) { // for each color in the map
cout << "Color" << x.first << " : "; // display the color (key)
for (auto y : x.second) // and iterate through the vector of position
cout << y << " ";
cout << endl;
}
You don't know for sure how many different color codes you have, but you want to store for accodes