Trouble passing 2D array in C++ 8 Puzzle - c++

For some reason I can't get the distance function to work. Could someone explain to me what I am doing wrong?
Main Function:
#include <iostream>
#include <cmath>
using namespace std;
int distance(int**, int);
int main()
{
int m;
int goal [3][3] = { {1,2,3},{4,5,6},{7,8,0}};
const int N = 3;
int intial[N][N];
cout << "Enter in values: \n";
for(int i=0; i<3; i++) //This loops on the rows.
{
for(int j=0; j<3; j++) //This loops on the columns
{
cin >> intial[i][j];
}
}
cout << goal[0][0] << "\n" ;
m = distance(intial,N);
system("PAUSE");
return 0;
}
Manhattan Distance calculation!
int distance(int** array,int N)
{
int MSum = 0;
for (int x = 0; x < N; x++){ //Transversing rows(i)
for (int y = 0; y < N; y++) { //traversing colums (j)
int value = array[x][y]; // sets int to the value of space on board
if (value != 0) { // Don't compute MD for element 0
int targetX = (value - 1) / N; // expected x-coordinate (row)
int targetY = (value - 1) % N; // expected y-coordinate (col)
int dx = x - targetX; // x-distance to expected coordinate
int dy = y - targetY; // y-distance to expected coordinate
MSum += abs(dx) +abs(dy);
}
}
}
int m = MSum;
return m;
}

This looks basically correct as far as logic goes. The array you pass in should be compatible with the function declaration and implementation. Here is a sample declaration:
int distance(int array[3][3],int N);

Related

Rotate a 2-D array by 90 degrees

How can I take the array size input from the user and pass it to the function. I tried #define inside the function, it doesn't work since the array definition needs the array bound at compile time. I tried global variable too, it says to define a integer constant which is not feasible in my case since I want to get the size from the user. How can I solve this issue?
#include <iostream>
using namespace std;
// reverse the transposed matrix as step 2
void reverseColumns(int arr[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N / 2; j++)
{
int temp = arr[i][j];
arr[i][j] = arr[i][N - j - 1];
arr[i][N - j - 1] = temp;
}
}
}
// take the transpose of matrix as step 1
void transposeMatrix(int arr[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = i; j < N; j++)
{
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
void rotateMatrix(int mat[N][N])
{
transposeMatrix(mat);
reverseColumns(mat);
}
// printing the final result
void displayMatrix(int mat[N][N])
{
int i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
cout << mat[i][j] << "\t";
cout << "\n";
}
cout << "\n";
}
int main()
{
int T, N;
cin >> T;
while (T > 0)
{
cin >> N;
int mat[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cin >> mat[i][j];
}
}
int res[N][N];
rotateMatrix(mat);
displayMatrix(mat);
}
return 0;
}
One way to make it work is get the input of rows and cols from user and make a one dimensional array dynamically.
for example:
Let ROWS and COLS be the values you got via cin.
Then the array can be declared as
int* arr = new int[ROWS * COLS];
Instead of writing arr[i][j] you have to write
arr[i * COLS + j]
Also you have to delete the array using
delete[] arr;
You are using C++ so you should take advantages of it. As kiner_shah commented the fast way to fix your code is just by use of std::vector<std::vector<int>>.
This is better solution but stil poor:
#include <iostream>
#include <vector>
using namespace std;
using Matrix = std::vector<std::vector<int>>;
Matrix makeSquereMatrix(size_t N)
{
return {N, std::vector<int>(N)};
}
// reverse the transposed matrix as step 2
void reverseColumns(Matrix& arr)
{
auto N = arr.size();
... // no changes here
}
// take the transpose of matrix as step 1
void transposeMatrix(Matrix& arr)
{
auto N = arr.size();
... // no changes here
}
void rotateMatrix(Matrix& mat)
{
transposeMatrix(mat);
reverseColumns(mat);
}
// printing the final result
void displayMatrix(const Matrix& mat)
{
for (auto& row : mat)
{
for (auto x : row)
cout << x << "\t";
cout << "\n";
}
cout << "\n";
}
void readMatrix(Matrix& m)
{
for (auto& row : m)
{
for (auto& x : row)
{
cin >> x;
}
}
}
int main()
{
int T, N;
cin >> T;
while (T > 0)
{
cin >> N;
auto mat = makeSquereMatrix(N);
readMatrix(mat);
rotateMatrix(mat);
displayMatrix(mat);
--T;
}
return 0;
}
Live demo
Better solution would be introducing a class containing std:::vector with methods performing required actions.
BTW some time ago I've made some matrix code for C. Here is live demo

How to correctly use pointers in code

For the following code, how can I find [A^-1] using pointers(equation for [A^-1]= 1/ det (A)? I am not sure whether pointers are used in the arithmetic or if they are used to call a value. Explaining what a pointer would be nice as I'm not exactly sure what they even do. I have most of the code written, except for this one part, so any help is much appreciated. Thanks in advance.
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <bits/stdc++.h>
#define N 3
using namespace std;
template<class T>
void display(T A[N][N])
{
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << A[i][j] << "\t\t";
cout << endl;
}
}
template<class T>
void display(T A[N])
{
for (int i=0; i<N; i++)
{
cout << A[i]<< "\n";
}
}
void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = A[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinant(int A[N][N], int n)
{
int D = 0;
if (n == 1)
return A[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(A, temp, 0, f, n);
D += sign * A[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return D;
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
getCofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
bool inverse(int A[N][N]){
int det = determinant(A, N);
if (det == 0){
cout << "Singular matrix, can't find its inverse";
return false;
}
return true;
}
void computeInverse(int A[N][N], float inverse[N][N]){
int det = determinant(A, N);
int adj[N][N];
adjoint(A, adj);
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
inverse[i][j] = adj[i][j]/float(det);
cout<<"\nThe Inverse of the Matrix A is:"<<endl;
display(inverse);
}
int main()
{
system("cls");
int A[N][N] = {{-1, 4, -2}, {-3, -2, +1}, {+2, -5, +3}};
char X[N];
int B[N];
float inv[N][N];
cout<<"\nEnter a 3*3 Matrix A"<<endl;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin>>A[i][j];
}
}
cout<<"\nEnter variables x, y, z for Matrix X"<<endl;
for(int i=0;i<N;i++){
cin>>X[i];
}
if (X[0] == 'x' && X[1] == 'y' && X[2] == 'z')
cout<<"\nMatrix X is Valid"<<endl;
else{
cout<<"\nMatrix X is Invalid"<<endl;
return -1;
}
cout<<"\nEnter values for Matrix B"<<endl;
for(int i=0; i<N; i++)
cin>>B[i];
cout<<"\nMatrix A is:------->\n";
display(A);
cout<<"\nMatrix X is:------->\n";
display(X);
cout<<"\nMatrix B is:------->\n";
display(B);
bool isInverseExist = inverse(A);
if (isInverseExist)
computeInverse(A, inv);
return 0;
}
Okay, Here is a simple pointer example using a char array. This can work with other data types as well. Don't remember where I read it; Think of a pointer as an empty bottle.
lets break this down in English first then I'll share a simple example that can be compiled. Imagine that you have 10 m&m's sitting in front of you on a table.
These m&m's represent a character array that we will call char mm[10]; Assume that this array is filled with chars that represent the color of all 10 of the m&m's
Now, we don't want to leave our candy's on the table all day so we will store all ten of the m&m's in a special jar specifically made for the m&m's. this jar will be called char* mm_ptr;
So now we are left with a table of m&m's and a jar sitting next to the pile. The next step is to fill the jar with the m&m's and you do it like this: mm_ptr = mm;
You now have a "jar full of m&m's". This allows you to access the m&m's directly from the jar!
Here is a Working example of of putting m&m's into a jar:
#include <iostream>
//using namespace std;
int main(){//The main function is our table
char mm[10]; //Our pile of m&m's
for(int i=0; i<10; i++){
if(i < 5){
mm[i] = 'b'; //Lets say that half of the m&m's are blue
}else{
mm[i] = 'r'; //and that the other half is red
}
}
char* mm_ptr; //This is our bottle that we will
//use to store our m&m's
mm_ptr = mm; //this is us storing the m&m's in the jar!
for(int i=0; i<10; i++){//Lets dump those candies back onto the table!
std::cout<<mm_ptr[i]<<std::endl;
}
return 0;
}
A correctly initialized pointer will work almost exactly like a normal array

Having trouble implementing pseudocode for Subset Sum

so I am trying to implement the following pseudocode but it will not work as it is supposed to. Here is the problem description in the slide, "Given an integer bound, "W", and a collection of "n" items, each with a positive integer weight "wi", find a subset S of items that: maximizes Sigma sub i where i is an element of S "wi" while keeping this sum less than or equal or to W. I will attach the following slides for where I am getting the problem description and pseudocode from. The problem with my implementation is that it will only find the total max value and not the value that is less than or equal to the weight. So for example, if I had Weight 10 (W = 10) and items 3 (n = 3) with item weights 1, 4, & 8 then the following answer should be 9; however, my solution gives 12. Here are the slides (*Please not, where it says w[j] it is meant to be w[i] - the slide had a typo):
Here is my code that implements the pseudocode:
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int max(int a, int b, int c) {
if (a >= b)
return a;
else
return b;
}
int optimal_weight(int W, const vector<int> &wt, int n){
vector<vector<int> > M;
M.resize(n+1);
for(int i = 0; i < n+1; ++i){
M[i].resize(W+1);
}
for(int w = 0; w < W+1; w++){
M[0][w] = 0;
}
for(int i = 1; i < n+1; i++){
M[i][0] = 0;
}
for(int i = 1; i < n+1; i++){
for(int w = 0; w < W+1; w++){
if(wt[i] > w){
M[i][w] = M[i-1][w];
}
M[i][w] = max(M[i-1][w], wt[i] + M[i-1][W-wt[i]], W);
}
}
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= W; j++)
printf ("%4d", M[i][j]);
printf("\n");
}
return M[n][W];
}
int main()
{
//int val[] = {1, 1, 1};
int W;
int n;
cin >> W >> n;
vector<int> wt(n);
for(int i = 0; i < n; i++){
cin >> wt[i];
}
cout << optimal_weight(W, wt, n) << endl;
}
Thank you for any help!
I figured it out! Here is my solution:
#include <iostream>
#include <vector>
using namespace std;
using std::vector;
int optimal_weight(int W, const vector<int> &wt) {
//write your code here
int n = wt.size();
vector<vector<int> > matrix;
matrix.resize(W+1);
for(int i = 0; i < W+1; i++){
matrix[i].resize(n);
}
for(int j = 0; j < n; j++){
matrix[0][j] = 0;
}
for(int w = 0; w < W + 1; w++){
matrix[w][0] = 0;
}
for(int i = 1; i < n; i++){
for(int w = 1; w < W+1; w++){
matrix[w][i] = matrix[w][i-1];
if(wt[i] <= w){
//cout << wt[i] << endl;
int val = matrix[w-wt[i]][i-1] + wt[i];
if(matrix[w][i] < val){
matrix[w][i] = val;
}
}
}
}
return matrix[W][n-1];
}
int main() {
int n, W;
std::cin >> W >> n;
vector<int> wt(n+1);
for (int i = 1; i < n+1; i++) {
wt[0]=0;
std::cin >> wt[i];
}
std::cout << optimal_weight(W, wt) << '\n';
}

How to sort elements into C++ matrix?

I'm new to C++ programming. I need to sort this matrix:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
Mat10 a;
fillRand(a, 5, 5);
prnMat(a, 5, 5);
cout << endl;
return 0;
}
void fillRand(Mat10 m, int n, int k) {
for (int i = 0; i < n; i++)
for (int j = 0; j < k; j++)
m[i][j] = rand() % 1000;
}
void prnMat(Mat10 a, int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << setw(8) << a[i][j];
cout << endl;
}
}
I need to sort the matrix from the beginning from the beginning. The smallest value must be at the beginning of the of the first column. The next must be below it and so on. The result must be sorted matrix - the smallest number must be at the beginning of the left column - the biggest value must be at the end of the matrix. Would you please help to solve the problem?
EDIT
Maybe I found possible solution:
void sort(int pin[10][2], int n)
{
int y,d;
for(int i=0;i<n-1;i++)
{
for(int j=0; j<n-1-i; j++)
{
if(pin[j+1][1] < pin[j][1]) // swap the elements depending on the second row if the next value is smaller
{
y = pin[j][1];
pin[j][1] = pin[j+1][1];
pin[j+1][1] = y;
d = pin[j][0];
pin[j][0] = pin[j+1][0];
pin[j+1][0] = d;
}
else if(pin[j+1][1] == pin[j][1]) // else if the two elements are equal, sort them depending on the first row
{
if(pin[j+1][0] < pin[j][0])
{
y = pin[j][1];
pin[j][1] = pin[j+1][1];
pin[j+1][1] = y;
d = pin[j][0];
pin[j][0] = pin[j+1][0];
pin[j+1][0] = d;
}
}
}
}
}
But since I'm new to programming I don't understand is this the solution?
Here is a simple example for you:
#include <vector>
#include <algorithm>
using namespace std;
//This is the comparation function needed for sort()
bool compareFunction (int i,int j)
{
return (i<j);
}
int main()
{
//let's say you have this matrix
int matrix[10][10];
//filling it with random numbers.
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
matrix[i][j] = rand() % 1000;
//Now we get all the data from the matrix into a vector.
std::vector<int> vect;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
vect.push_back(matrix[i][j]);
//and sort the vector using standart sort() function
std::sort( vect.begin(), vect.end(), compareFunction );
//Finally, we put the data back into the matrix
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
matrix[i][j] = vect.at(i*10 + j);
}
After this, the matrix will be sorted by rows:
1 2
3 4
If you want it to be sorted by cols:
1 3
2 4
You need to replace matrix[i][j] in the last cycle only with matrix[j][i]
If you need to read about the the sort() function, you can do it here
Hope this helps.
You can simply call std::sort on the array:
#include <algorithm> // for std::sort
int main() {
int mat[10][10];
// fill in the matrix
...
// sort it
std::sort(&mat[0][0], &mat[0][0]+10*10);
}

Why is the axis for my program off

//============================================================================
// Name : Assignment.cpp
// Author : Tim Bialecki
// Version :
//============================================================================
#include <iostream>
#include <math.h>
using namespace std;
void circle(int x, int y, int radius);
void line(int a, int b, int c, int d);
bool buffer[26][81];
char drawSpace[26][81];
int main() {
int a = 75;
int b = 5;
int c = 4;
int d = 26;
/*cout << "please enter an x coordinate for the center of the circle";
cin >> x;
cout << "please enter a y coordinate for the center of the circle";
cin >> y;
cout << "please enter a value for the radius of the circle";
cin >> radius;*/
circle(a, b, c);
for (int col = 80; col >= 0; col--) {
for (int row = 25; row >= 0; row--) {
cout << drawSpace[row][col];
}
cout << "\n";
}
return 0;
}
void circle(int x, int y, int radius){
/*if (x + radius >= 81 || y + radius >= 26 || y - radius <= 26){
cout << "the coordinates provided for the circle will not fit on the screen" << endl;
return;
}*/
for (int i = 0; i < 26; i++) {
for(int j = 0; j < 81; j++) {
int a = abs (x - j);
int b = abs (y - i);
int distance = pow(a, 2) + pow(b, 2);
int realDistance = pow(radius, 2);
if (abs(realDistance - distance) <= 3){
buffer[i][j] = true;
}
}
}
for (int m = 0; m < 26; m++){
for(int n = 0; n < 81; n++){
if (buffer[m][n]){
drawSpace[m][n] = 42;
}
else
drawSpace[m][n] = 32;
}
}
}
void line(int a, int b, int c, int d){
int intercept = 0;
double rise = d - b;
double run = c - a;
double slope = rise/run;
intercept = b - (slope*a);
for (int i = 0; i < 26; i++) {
for(int j = 0; j < 81; j++) {
int newIntercept = i - (slope*j);
int test = abs (intercept - newIntercept);
if (test <= 0)
buffer[i][j] = true;
else
buffer[i][j] = false;
}
}
for (int m = 0; m < 26; m++){
for(int n = 0; n < 81; n++){
if (buffer[m][n])
drawSpace[m][n] = 42;
else
drawSpace[m][n] = 32;
}
}
}
This code is a work in progress, but I'm trying to write a program that takes inputs for the coordinates and dimensions of both a line and a circle and prints them out in the terminal window as if it were a 81x26 graph. I have just supplied sample inputs to test this out, but for some reason the shapes are not printing with the appropriate orientation to what should be the x and y axises. I have tried a bunch of different ways of trying to fix this problem and have had no luck. Hoping someone can help. Thanks
Looks OK to me:
***
** **
* *
* *
* *
* *
* *
** **
***
It's not perfectly round because characters are taller than they are wide.
EDIT: That's only the first few rows on my output. Based on the comment and a second look at the code, I think rows and columns are getting mixed up.
for (int col = 80; col >= 0; col--) {
for (int row = 25; row >= 0; row--) {
cout << drawSpace[row][col];
}
cout << "\n";
}
There's a newline after every "column". Swapping the two for lines may produce what you want.