I'm new to C++ programming.
Now I have the state class. I want to create neighboring states with this class, so I add the function getNeighboringStates() to my class. In this function I pass in "neighboring_states" to function set_neighboring_state(), this function change "neighboring_states"'s value.
In this function, I set a for loop to test. It print out "7 1 0 3 6 4 5 2 8", which is the value I want. But In the function getNeighboringStates(), I also set a for loop that has the same mission as in set_neighboring_state(), but the screen display "0 1 4716672 2686652 2686528 0 4716676 4519501 4716676".
I don't know what's wrong with my code. What do I need to do now?
int n; // The number of columns as well as rows of the board
int k; // The kind of heuristic function to use
int tilesCount; // The number of tiles, including the blank one
int statesCount; // The number of states generated
int* m_initTiles;
int* m_goalTiles;
int tmpTile;
const int UP = 0;
const int DOWN = 1;
const int RIGHT = 2;
const int LEFT = 3;
int* direction;
class State {
public:
State(){}
int getBlankTilePosition() {
for (int i = 0; i < n * n; i++) {
if (stateTiles[i] == 0)
return i;
}
}
void set_neighboring_state(State* neighboring_state, int direction) {
int blankPosition = getBlankTilePosition();
int neighbor_tiles[n * n];
for (int i = 0; i < n * n; i++) {
neighbor_tiles[i] = getStateTiles()[i];
}
switch(direction) {
case UP:
if (blankPosition/n < 1) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition - n]);
neighboring_state->set_tiles(neighbor_tiles);
// This for loop print out "7 1 0 3 6 4 5 2 8"
for (int i = 0; i < n * n; i++)
cout << neighboring_state.getStateTiles()[i] << " "; cout << endl;
}
break;
case DOWN:
if (blankPosition/n == n - 1) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition + n]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
case LEFT:
if (blankPosition % n == 0) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition - 1]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
default:
if ((blankPosition + 1) % n == 0) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition + 1]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
}
}
/*
The maximum number of neighboring state that can be created is 4.
This function return the neighboring states of a certain state.
The first state represents for the "left" neighbor, the second,
the third and the fourth represent the "right", "up, and "down"
neighbor, respectively.
*/
State* getNeighboringStates() {
State* neighboring_states;
neighboring_states = new State[4];
for (int i = 0; i < 4; i++)
set_neighboring_state(&neighboring_states[i], direction[i]);
// This print out "0 1 4716672 2686652 2686528 0 4716676 4519501 4716676"
cout << endl;
for (int i = 0; i < n * n; i++)
cout << neighboring_states[0].getStateTiles()[i] << " ";
cout << endl;
return neighboring_states;
}
State(int* pStateTiles) {
stateTiles = pStateTiles;
}
void set_tiles(int* tiles) {
stateTiles = tiles;
}
int* getStateTiles() {
return stateTiles;
}
private:
int* stateTiles;
};
void input(const char* fileName) {
ifstream fin;
fin.open(fileName);
// read n, k from file
fin >> n >> k;
// allocate m_initTiles and m_goalTiles memory
m_initTiles = new int[n * n];
m_goalTiles = new int[n * n];
for (int i = 0; i < n * n; i++)
fin >> m_initTiles[i];
for (int i = 0; i < n * n; i++)
fin >> m_goalTiles[i];
for (int i = 0; i < n * n; i++)
cout << m_initTiles[i] << " ";
cout << endl;
for (int i = 0; i < n * n; i++)
cout << m_goalTiles[i] << " ";
cout << endl;
fin.close();
}
void initDirection() {
direction = new int[4];
direction[0] = UP;
direction[1] = DOWN;
direction[2] = RIGHT;
direction[3] = LEFT;
}
int main() {
input("nPuzzle.inp");
initDirection();
State init_state (m_initTiles);
State goal_state (m_goalTiles);
State* init_neighbor = init_state.getNeighboringStates();
// int* state_tile = init_neighbor[0].getStateTiles();
// for (int i = 0; i < n * n; i++)
// cout << state_tile[i] << " ";
return 0;
}
int blankPosition = getBlankTilePosition();
int neighbor_tiles[n * n];
Remove int neighbor_tiles[n * n]; line from above code segment and make it global available to all function , so declare it as data of a class not for function i.e. add int neighbor_tiles[n * n]; to class as an data type .
Related
Normally I would use other methods to fix this program but I am not allowed to use advanced techniques for this project, and so what I have is more or less as far as I'm allowed to go.
So my program is meant to take in an array with 10 numbers and then output how many of each value is in the array. For example, {1, 1, 1, 1, 1, 2, 2, 2, 2, 2} is meant to return
5 1
5 2
However, it returns
6 1
4 2
I've made sure that the finalData and Data arrays are holding the proper values.
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
seems to be outputting the wrong value.
for some reason. I believe the error is in my last function, getResults, more specifically the last for loop. Here is that function.
void getResults(int finalData[], int data[])
{
int temp[MAX_VALUE];
int j = 0;
for (int i = 0; i < MAX_VALUE - 1; i++)
if (finalData[i] != finalData[i + 1])
temp[j++] = finalData[i];
temp[j++] = finalData[MAX_VALUE - 1];
for (int i = 0; i < j; i++)
{
finalData[i] = temp[i];
}
for (int i = 0; i < j; i++)
{
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
}
}
This is my complete code.
#include<iostream>
#include<iomanip>
#include<string>
#include<cmath>
#include <algorithm>
using namespace std;
void printHeader();
int getData(string);
void getResults(int finalData[], int data[]);
const int MAX_VALUE = 10;
int main(void)
{
int countValue = 0;
int freq = 0;
printHeader();
int data[MAX_VALUE] = {};
int frequency[MAX_VALUE] = {};
for (int i = 0; i < MAX_VALUE; i++)
{
cout << "Please enter data position " << i + 1 << "\n";
data[i] = getData("\nPlease enter a valid integer.\n");
}
sort(data, data + MAX_VALUE);
int values[MAX_VALUE] = {};
int secondData[MAX_VALUE] = {};
for (int i = 0; i < MAX_VALUE; i++)
{
secondData[i] = data[i];
}
getResults(data, secondData);
return 0;
}
void printHeader()
{
}
int getData(string error)
{
int userInput = 0;
do
{
cin >> userInput;
if (cin.fail())
{
cout << error;
}
} while (cin.fail());
return userInput;
}
void getResults(int finalData[], int data[])
{
int temp[MAX_VALUE];
int j = 0;
for (int i = 0; i < MAX_VALUE - 1; i++)
if (finalData[i] != finalData[i + 1])
temp[j++] = finalData[i];
temp[j++] = finalData[MAX_VALUE - 1];
for (int i = 0; i < j; i++)
{
finalData[i] = temp[i];
}
for (int i = 0; i < j; i++)
{
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
}
}
Got the right answer. Made the changes I listed at the top as well as the following change to the count function.
cout << count(data, data + MAX_VALUE, finalData[i]) << " " << finalData[i] << "\n";
You have done a simple error. When you call getResults you pass the same array(pointer) to 2 different parameters. Now when you update finalData the unwanted side effect update also data(they are the same pointer(with different name). So when you call count will not return the expected result.
To solve this problem you can do a copy of the input array and give it as second parameter of getResults(...) function.
I used a 'bubble-sort' for my C++ program, but it introduces random '0' values in array in a Fractional Greedy Program
int sorteaza()
{
int aux,schimb,i;
do
{
schimb=0;
for (i=0;i<=n;++i)
if (G[i][3]<G[i+1][3])
{
swap(G[i], G[i+1]);
}
}
while (schimb);
}
This is my entire code:
#include<iostream>
using namespace std;
int n; // Numarul de elemente
float G[100][3]; // Obiecte + detalii masa profit potenta
int masa = 0;
int read_data()
{
cout << "Greutatea Rucsac" << endl;
cin >> masa;
cout << "Obiecte: " << endl;
cin >> n;
for(int i = 1; i<=n;i++)
{
for(int j = 1; j<=2;j++)
{
cin >> G[i][j];
if(G[i][1] != 0 && G[i][2] != 0)
{
G[i][3] = G[i][2] / G[i][1];
}
}
}
}
// 2 500
// 4 500
int sorteaza()
{
int aux,schimb,i;
do
{
schimb=0;
for (i=0;i<=n;++i)
if (G[i][3]<G[i+1][3])
{
swap(G[i], G[i+1]);
}
}
while (schimb);
}
int verify()
{
for(int i = 1; i<=n;i++)
{
for(int j = 1; j<=3;j++)
{
cout << G[i][j];
cout << endl;
//G[i][3] = G[i][1] / G[i][2];
}
}
}
int greedy()
{
float profit = 0;
int i = 1;
int aux;
while(i<=n && masa>=0)
{
//cout << "G[i][1]: " << G[i][1] << endl;
if(masa>=G[i][1]) {
//cout << "Am ajuns aici";
profit=profit+G[i][2];
masa=masa-G[i][1];
}
else {
//cout << "Am ajuns dincolo";
aux= (masa*100)/G[i][1];
profit = profit + (aux * G[i][2])/100;
break;
}
i++;
}
cout << profit;
}
int main()
{
read_data();
sorteaza();
verify();
// greedy();
}
Learn to index all your arrays from zero.
float G[100][3];
Legal indexes are 0 to 99 and 0 to 2. So this code should be
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> G[i][j];
}
if (G[i][0] != 0 && G[i][1] != 0)
{
G[i][2] = G[i][1] / G[i][0];
}
}
and this code should be
if (G[i][2] < G[i+1][2])
{
swap(G[i], G[i+1]);
}
All your arrays start at zero. I'm sure you've been told this, but you have to start putting it into practise.
In general, write your for loops like this
for (int i = 0; i < N; ++i)
That's the correct loop for an array of size N.
You probably need <n instead of ≤n (that's where the uninitialized value i.e. 0 comes from). And you miss one loop in the bubble sort. Right now you're only bubbling the smallest element to the end of the list.
Also no idea what you're doing with that schimb and while condition.
Furthermore you're defining G as float[100][3] so you can't use G[i][3], only G[i][2].
int sorteaza()
{
int i,j;
for (i=0; i<n; i++)
{
for (j=i+1; j<n; j++)
{
if (G[i][2] < G[j][2])
{
swap(G[i], G[j]);
}
}
}
}
I could not figure out why I got
*** Error in `./a.out': free(): invalid next size (fast): 0x00000000006db0e0 ***
while trying to free g, u and subset arrays declared inside subs_sum function in the following code:
#include <iostream>
#include <algorithm>
#include <new>
using namespace std;
int
subs_sum(int n, int * numbers)
{
int * g = new int [n-1];
int * u = new int [n-1];
int * subset = new int [n-1];
int i, j;
int sum = 0, nelem = 0;
int found = 0;
for (i=0; i<=n-1; i++)
{
g[i] = 0;
u[i] = 1;
}
do
{
i = 0;
j = g[0] + u[0];
while ((j>=2) || (j<0))
{
u[i] = -u[i];
i++;
j = g[i] + u[i];
}
if (g[i])
{
g[i] = 0;
nelem--;
sum -= numbers[i];
}
else
{
g[i] = 1;
nelem++;
sum += numbers[i];
}
if (g[n-1]) break;
if (sum == numbers[n-1])
{
if (nelem == n-1) // Success!!!
{
// Print partial result
for (int ll=0; ll<=n-2; ll++)
if (g[ll]) cout << numbers[ll] << "+";
cout << "\b=" << sum << endl;
found = 1;
break;
}
if (n-1-nelem >= 2) // Go deeper.
{
int pp = 0;
for (int ll=0; ll<=n-2; ll++)
if (! g[ll]) subset[pp++] = numbers[ll];
if (subs_sum(n-1-nelem, subset)) // Match found!!!
{
// Print partial result
for (int ll=0; ll<=n-2; ll++)
if (g[ll]) cout << numbers[ll] << "+";
cout << "\b=" << sum << endl;
found = 1;
break;
}
}
}
}
while(1);
delete [] g;
delete [] u;
delete [] subset;
return found;
}
int
main(void)
{
int * numbers;
int i;
cin >> i;
numbers = new int [i];
for (int j=0; j<i; j++)
cin >> numbers[j];
cout << "Sorted Numbers: ";
sort(numbers, numbers+i);
for (int j=0; j<i; j++)
cout << numbers[j] << " ";
cout << endl;
subs_sum(i, numbers);
delete [] numbers;
return 0;
}
I got no one issue if I comment out
delete [] g;
delete [] u;
delete [] subset;
and program ran as expected:
$ echo -e "11\n1\n41\n10\n24\n5\n12\n6\n14\n9\n35\n7\n" | ./a.out
Sorted Numbers: 1 5 6 7 9 10 12 14 24 35 41
1+5=6
9+12+14=35
7+10+24=41
Any idea? Thanks
you are not making your arrays big enough. Allocate them as new int[n] instead of new int[n-1]
int * g = new int [n-1];
Allocates an array of n-1 int, indices 0 to n-1-1.
Later, you access:
for (i=0; i<=n-1; i++)
{
g[i] = 0;
u[i] = 1;
}
Which is in the last iteration:
g[n-1] = 0;
Buffer overrun is a common case of undefined behavior, which means anything may happen.
Seems in this case you scrambled the bookkeeping of your allocator, which was actually diagnosed.
Such a happy outcome cannot be guaranteed.
Why does it say free found the error, and not delete?
Well, the delete-expression under the covers calls the dtor on the object (unless trivial aka no-op as for primitive types) and then the function operator delete.
The latter commonly just forwards the request to free.
void CensusData::mergeSort(int type) {
if(type == 0)
MERGE_SORT(type, 0, data.size());
}
void CensusData::MERGE_SORT(int type, int p, int r){
//int q;
//cout << "data size " << data.size() << endl;
std::cout << "MERGE_SORT START ///("<< p << ", " << r << ")" <<std::endl;
if(p < r)
{
int q = (p + r)/2;
MERGE_SORT(type, p, q);
MERGE_SORT(type, q + 1, r);
MERGE(type, p, q ,r);
}
}
void CensusData::MERGE(int type, int p, int q, int r){
if(type == 0)
{
std::cout << "MERGING" << std::endl;
//int n1;
//int n2;
int n1 = q - p + 1;
int n2 = r - q;
int L[n1 + 1];
int R[n2 + 1];
for(int i = 1; i < n1; i++)
{
cout << "filling Left Array" << endl;
L[i] = data[p + i - 1]->population;
}
for(int j = 1; j < n2; j++)
{
cout << "filling Right Array" << endl;
R[j] = data[q + j]->population;
}
int i = 1;
int j = 1;
for(int k = p; p < r; p++)
{
cout << "for loop: " << endl;
if(L[i] <= R[j])
{
cout << "TRUE" << endl;
data[k]->population = L[j];
i = i + 1;
}
/*else if(data[k]->population == R[j])
{
cout << "FALSE" << endl;
j = j + 1;
}*/
else
{
data[k]->population = R[j];
j = j + 1;
}
}
}
}
do not worry about type, it wont effect this program at all. basically i am trying to make a merge sort that will take a vector containing an integer, the vector looks like this:
class Record { // declaration of a Record
public:
std::string* city;
std::string* state;
int population;
Record(std::string&, std::string&, int);
~Record();
};
std::vector<Record*> data;
basically i have been trying to get it to actually sort, but it doesn't seem to work at all, i have even seen garbage in the program.
example input:
237 812826 68642
output:
4484540 812826 68642
Note: all of the rest of the program works fine (tested it with an insertion sort) only this part is not working.
Take a look at lecture 15 of the excellent Stanford Universities course Programming Abstractions. It covers all kinds of sorts including merge:
http://see.stanford.edu/see/lecturelist.aspx?coll=11f4f422-5670-4b4c-889c-008262e09e4e
You can even get the source code from SourceForge:
http://sourceforge.net/projects/progabstrlib/files/
My code is below. The problem happens when I try and run the addArray() function. I am completely new to C++ so I have no idea what a segmentation fault means.
I also know that there is probably a better way to initialize and return the 2d arrays, but I am slowly figuring that out.
My main problem now is the segmentation fault. I am guessing that it has something to do with how I am accessing the variables?
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
using namespace std;
int c, q, w, row, coll, quit, qq, opt;
int** arr1;
int** arr2;
int** ans;
//Method Prototypes
int menu();
inline int** getArray(int opt);
inline void printArray(int** arr, int height, int width);
void addArray();
void subtractArray();
void multiplyArrays();
void determArray();
void transposeArray();
void inverseArray();
//Prints out the menu for choosing which option to go with
int menu() {
cout << "Press 1 for Addition\n";
cout << "Press 2 for Subtraction\n";
cout << "Press 3 for Multiplication\n";
cout << "Press 4 for Determinant\n";
cout << "Press 5 for Transpose\n";
cout << "Press 6 for Inverse\n";
cout << "Press 0 to quit\n\n";
cin >> c;
return c;
}
//Main method
int main(void) {
cout << "C++ 2d Matrix Operations Menu\n";
c = menu();
while (c != 0) {
if (c == 1) {
addArray();
} else if (c == 2) {
subtractArray();
} else if (c == 3) {
void multiplyArrays();
} else if (c == 4) {
void determArray();
} else if (c == 5) {
void transposeArray();
} else if (c == 6) {
}
c = menu();
}
cout << "Press Enter to Quit. GOOD BYE";
cin >> quit;
return 0;
}
/*
Prints out the specified array.
It's arguments are the actual array and the height/weight
*/
inline void printArray(int** arr, int height, int width) {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
std::cout << arr[i][j] << ' ';
}
std::cout << std::endl;
}
}
//Returns an array.
inline int** getArray(int opt) {
if (opt == 0) {
cout << "How many rows and columns should be in the array?\n";
cin >> q >> w;
} else {
q = 3;
w = 3;
}
int** ary = new int*[q];
for (int i = 0; i < q; ++i) {
ary[i] = new int[w];
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
cout << "What should the value be for item" << row << "," << coll << "\n";
cin >> ary[row][coll];
}
}
return ary;
}
//Adds arrays
void addArray() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
arr2 = getArray(0);
int h2 = q;
int w2 = w;
if ((h1 != h2) || (w1 != w2)) {
cout << "Both arrays must be the same size.";
return;
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[row][coll] + arr2[row][coll];
}
}
printArray(ans, q, w);
}
//Subtracts Arrays
void subtractArray() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
arr2 = getArray(0);
int h2 = q;
int w2 = w;
if ((h1 != h2) || (w1 != w2)) {
cout << "Both arrays must be the same size.";
return;
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr2[row][coll] - arr1[row][coll];
}
}
printArray(ans, q, w);
}
//Calculate the determinate of an array.
void determArray() {
arr1 = getArray(1);
printArray(arr1, q, w);
//There must be a better/more efficient way to do this using loops.
int determinant = arr1[0][0]*((arr1[1][1] * arr1[2][2]) - (arr1[2][1] * arr1[1][2])) - arr1[0][1]*(arr1[1][0] * arr1[2][2] - arr1[2][0] * arr1[1][2]) + arr1[0][2]*(arr1[1][0] * arr1[2][1] - arr1[2][0] * arr1[1][1]);
printf("\nDeterminant of vector using method 1 is: %d\n", determinant);
}
//Transpose an array.
void transposeArray() {
cout << "IN TRANS";
arr1 = getArray(0);
printArray(arr1, 3, 3);
//Flip the values
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[coll][row];
}
}
cout << "----------" << endl << "The new vector looks like: \n";
printArray(ans, q, w);
}
/*
Multiply arrays. One option is to just multiply it by a number and the other is to multiply it by another array.
*/
void multiplyArrays() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
cout << "Do you wish to multiply the first vector by a number(Enter 1), or by a second vector(Enter 2)?";
cin >> qq;
int mu;
//First Option is to multiply it by a single number
if (qq == 1) {
cout << "What number do you wish to multiply the vector by?";
cin >> mu;
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[row][coll] * mu;
}
}
printArray(ans, h1, w1);
//Multiply two arrays
} else if (qq == 2) {
arr2 = getArray(0);
int h2 = q;
int w2 = w;
int n1 = h1;
int n2 = w2;
int nCommon = n1;
if (n2 == nCommon) {
cout << "Amount of columns for vector 1 must match amount of rows for vector 2";
return;
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
for (int k = 0; k < nCommon; k++) {
ans[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
printArray(ans, n1, n2);
}
}
You never allocate memory for ans. Just like you need to allocate storage for the two input arrays before filling them, you need to allocate storage for the answer.
A segmentation fault is generated when you attempt to write to memory that you do not have access to. In this case, because the ans array was not initialized, it points to random memory. When you do ans[row][coll] = arr2[row][coll] - arr1[row][coll];, you get a segfault because ans[row][col] is pointing somewhere outside your program space.
The problem is that you have not allocated memory for the ans array, but you are writing to it in the following code:
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr2[row][coll] - arr1[row][coll];
}
}
This is why you have segmentation fault.
Try to add a block to allocate memory for ans at first.