Replacing values in a 2D array - c++

I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?

If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.

You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.

The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)

Related

Problem in rearranging rows and columns of an array

In general, given the task:
A permissible matrix transformation is a permutation of two adjacent rows or two neighboring columns. A real square matrix of order n (n <= 12) is given. Using valid converters, you can get a matrix in which the maximum element is in the upper left corner. Elements were used to perform valid conversions.
My problem is precisely that I cannot swap adjacent rows or columns.
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
const int rows = 4, cols = rows;
int iMax = 0;
int jMax = 0;
int arr[rows][cols];
void arr_f()
{
setlocale(LC_ALL, "rus");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
if (arr[i][j] > arr[iMax][jMax])
{
iMax = i;
jMax = j;
}
}
cout << endl;
}
cout << endl << "The maximum number of array: " << arr[iMax][jMax] << endl << endl;
}
int main()
{
arr_f();
system("pause");
}
Tried to add features
inline void swap_columns(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][f], arr[i][s]);
}
}
inline void swap_rows(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[f][i], arr[s][i]);
}
}
and add the following to the arr_f () function:
swap_rows(0, iMax);
swap_columns(0, jMax);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
}
cout << endl;
}
But in this case, the rows (and columns) do not change as expected (the row in which the maximum value is located is immediately replaced by the first row, ignoring the rest).
You obtained a wrong result, because swap_columns and swap_rows make operations that are not allowed. You need to make them this way:
inline void swap_columns(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][k], arr[i][k+1]);
}
}
inline void swap_rows(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[k][i], arr[k+1][i]);
}
}
And apply this way:
for (int k = iMax-1; k >= 0; --k)
swap_rows(k);
for (int k = jMax-1; k >= 0; --k)
swap_columns(k);
Certainly, this may be improved by moving larger blocks, but this is a matter of optimization.
To swap adjacent rows and columns, just replace this:
swap_rows(0, iMax);
swap_columns(0, jMax);
with this:
swap_rows(iMax + 1, iMax);
swap_columns(jMax + 1, jMax);
However, it is not clear from the problem description, whether this would always be the desired solution. And if iMax happens to be the last row index, then iMax + 1 would be out of bounds and fail at run time. In that case, perhaps iMax - 1 would be required instead.

C++ Bubble Sort Using Swap Function and Pointers

I'm having problems figuring out where my bubble sort code went wrong. I'm almost positive it's in the sorting algorithm. Here is what I need my code to accomplish:
-Initialize an array a fill it with random numbers (I use getNumbers() to accomplish this)
-Compare the first element with all later elements. If the first element is larger, swap them.
-Compare the second element with all later elements one by one. If the second element is larger, swap them.
-Continue comparing and swap operations until the second to last element.
-Print out the sorted array
And here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main()
{
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[i], &array[j]);
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2)
{
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size)
{
int *array;
array = new int[size];
srand(time(0));
for(int i = 0; i < size; i++)
{
array[i] = rand() % 100;
}
return array;
}
Here is the correct code.
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main() {
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < (arraySize - 1); j++) {
if (array[j] > array[j + 1]) {
/*********** This line was changed ***********/
swap(&array[j+1], &array[j]); // You were earlier swapping ith and jth entries.
/*********************************************/
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2) {
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size) {
int *array;
array = new int[size];
srand(time(0));
for (int i = 0; i < size; i++) {
array[i] = rand() % 100;
}
return array;
}
You were swapping array[i] with array[j] in line 32. array[j] and array[j+1] should be swapped. Also, as pointed out by dd2, your loop bounds are not strict. The code would work correctly nonetheless but would take more steps. You can change the bound to j < (arraySize - i - 1)
Your loop bounds are not correct and swapping was wrong as well.
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - i - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[j], &array[j+1]);
}
}
}

Sorting 2D Dynamic Array C++

I am trying to sort a two dimensional dynamic array when row 1 is for product ID and row 2 is for the product price. I want to sort by product ID, and have the results displayed formatted with width of 5. Here is my code:
This section is fine and does what I am looking for:
void readData (int**, int, int);
void printData(int**, int, int);
void sortbyPartID(int**, int, int);
int main()
{
int index;
int **PriceSheet, rows, columns;
cout << "Enter the number of Products, and then the number of values associated with the products: ";
cout << "For default values, enter 5 (FIVE ITEMS, and enter 2 (TWO Values: ID and PRICE). ";
cin >> columns >> rows;
cout << endl;
PriceSheet = new int* [rows];
for (int row = 0; row < rows; row++)
PriceSheet [row] = new int[columns];
readData (PriceSheet, rows, columns);
cout << endl;
printData(PriceSheet, rows, columns);
sortbyPartID(PriceSheet, rows, columns);
return 0;
}
void readData (int **p, int rowSize, int colSize)
{
for (int row = 0; row < rowSize; row++)
{
cout << "Row ZERO is the Product ID and Row 1 is the Product Price\n";
cout << "Enter " << colSize << " numbers for the row number " << row << ": ";
for (int col = 0; col < colSize; col++)
cin >> p[row][col];
cout << endl;
}
}
void printData (int **p, int rowSize, int colSize)
{
cout << "\n\nThese are the Products IDs and Prices as entered in the system:\n";
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
THIS SECTION IS WHERE I NEED HELP
It reads correctly and prints the unsorted array also correctly, but I cannot figure out a way to sort the array. Specifically speaking, I need help on the void sortbyPartID function. I would like to use bubble sort, and I cannot figure out how to get this function to work. Any help with the sorting function/algorithm would be greatly appreciated.
void sortbyPartID (int **p, int rowSize, int colSize)
{
int swap = -1;
int end = colSize;
int sortedID = **p;
cout << "\n\nThese are the Products sorted Products IDs:\n";
for (int counter = colSize -1; counter >= 0; counter --)
for (int index = 0; index < end ; index ++)
{
if (sortedID[index] > sortedID[index + 1])
{
swap = *sortedID[index + 1];
sortedID[index + 1] = sortedID[index];
*sortedID[index] = swap;
}
}
for(int index = 0; index < end; index++)
{
cout << sortedID[index] << ", ";
}
cout << endl;
end --;
}
When I run, I get some weird results on the last section. Maybe I am missing something simple, not sure.
We can also perform this using do-while as follows:
bool isSwaped;
do
{
isSwaped = false;
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
int swap = p[index + 1][0];
p[index + 1][0] = p[index][0];
p[index][0] = swap;
isSwaped = true;
}
}
} while (isSwaped);
You can simplify the entire thing by using objects. Objects allow you to handle the related data in a sane fashion. Also highly recommend are vectors instead of C arrays.
struct Product {
int id;
int price;
vector<int> others;
}
You can then store your products in vector<Product> my_products; and then sorting everything with
std::sort(my_products.begin(), my_products.end(),
[](const Product& a, const Product& b) { return a.id < b.id; });
You can keep the existing input/output format, but place the values in the right place. This way it's almost impossible to mess up the attributes and everything is easy to work with.
int sortedID = **p; is not what you want, and should be removed. (I think you wanted int** sortedID = p;)
Your bubble-sort should be something like:
for (int counter = colSize -1; counter >= 0; --counter)
{
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
// std::swap(p[index], p[index + 1]);
int* swap = p[index + 1];
p[index + 1] = p[index];
p[index] = swap;
}
}
}
Live Demo

Choose the starting point of the Origin?

I was wondering if it was possible to move the starting point of the Origin to the bottom-left-corner of my grid.
This is the code I'm working with:
#include <iostream>
using namespace std;
char **createBoard(int n, int m); // Býr til tvívítt kvikt fylki og skilar því til baka
void initiaizeBoard(char **p, int n, int m); // Upphafsstillum allt með '.'
void printBoard(int n, int m, char **p); // Prentum út leikborðið
int main()
{
int rows, columns;
int xhnit;
int yhnit;
cin >> rows >> columns >> xhnit >> yhnit;
char **board = createBoard(rows, columns);
initiaizeBoard(board, rows, columns);
board[xhnit][yhnit] = player;
printBoard(rows, columns, board);
return 0;
}
char **createBoard(int n, int m)
{
char **p = new char*[n];
for (int i = 0; i < n; i++)
{
p[i] = new char[m];
}
return p;
}
void initiaizeBoard(char **p, int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
p[i][j] = '.';
}
}
}
void printBoard(int n, int m, char** p)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << p[i][j];
}
cout << endl;
}
}
For the input "10 10 5 6" my output is as follows:
..........
..........
..........
..........
..........
......X...
..........
..........
..........
..........
The Origins is now set in the top left corner as you can see from the output. I've been searching on this site and the internet in general and I can't seem to figure this out.
In a way, top-left and bottom-left are just arbitrary distinctions before you print the array. The array elements don't really have a physical location before you assign them one. So, in order to move the origin you can just print the rows from first to last.
void printBoard(int n, int m, char** p)
{
for (int i = n-1; i >= 0; i--)
{
for (int j = 0; j < m; j++)
{
cout << p[i][j];
}
cout << endl;
}
}
You can treat everything the same and simply print the rows in reverse order:
void printBoard(int n, int m, char** p) {
for (int i = n-1; i > -1; i--) { // Print in reverse order!
for (int j = 0; j < m; j++) {
cout << p[i][j];
}
cout << endl;
}
}
Here is a live example: http://ideone.com/GJVw8M
I am probably misunderstanding the question but is it just the output display that needs to change?
void printBoard(int n, int m, char** p)
{
for (int i = (n-1); i >=0; i--)
{
for (int j = 0; j < m; j++)
{
cout << p[i][j];
}
cout << endl;
}
}

Non Square Matrix Multiplication Help C++

first off sorry for the slightly messy code as I was fiddling with different things to try to get it to work. As of now, my code can multiply Square Matrices just fine; however, it has difficulties computing Non Square Matrices. My best guess after debugging is how i re-size my vectors, and that there is an out of bounds error which causes the program to crash. Any help would be appreciated, my code should be able to Multiply any Vectors sizes withing Matrix Multiplication Rules.
I also would like to note this is a HW assignment so I am limited to how I can build my code, basically ONLY using vectors, cannot write your own class etc....
#include <iostream>
#include <vector>
using namespace std;
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2);
void setMatrix(vector <vector<int> > &matrix, int rows, int cols);
int main()
{
int rows, cols, rows2, cols2;
vector< vector<int> > matrix, matrix2;
cout<<"Please enter the number of Rows and Columns for your first Matrix."<<endl;
cout<<"Rows: ";
cin>>rows;
cout<<"Columns: ";
cin>>cols;
matrix.resize(cols, vector<int>(rows,0)); //Saw this online so not sure how it works but it works, if i take out one i cant do row<column and vice versa
matrix.resize(rows, vector<int>(cols,0));
cout<<"Size has been declared, please enter data for your matrix"<<endl;
setMatrix(matrix,rows,cols);
cout<<"Second Matrix Automatically Set by Matrix Multiplication Rule"<<endl; //Just automatically sets second matrix as per Matrix Multiplication Rule
rows2=cols;
cols2=rows;
cout<<"Second Matrix Size is: " << rows2 << " by " << cols2 << endl;
matrix2.resize(cols2, vector<int>(rows2,0));
matrix2.resize(rows2, vector<int>(cols2,0));
setMatrix(matrix2,rows2,cols2);
cout<<"Multiplied Matrix is:"<<endl;
multiply_matrices(matrix,matrix2,cols,rows2);
system("PAUSE");
return 0;
}
void setMatrix(vector <vector<int> > &matrix, int rows,int cols){
int num;
for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j]=num;
}
cout << endl;
}
/*for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
*/
}
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2){
vector< vector<int> > tempMatrix;
int newrows=rows2;
int newcols=cols;
int sum;
tempMatrix.resize(newcols, vector<int>(newrows,0)); //Resizing new matrix to proper size, so if it was (2x3)(3x2), new matrix is (3x3)
for (int i = 0; i < newrows; i++) //This Works Fine for Square Matrixes but not for others, i have no clue how to fix it?
{
for (int j = 0; j < newcols; j++){
//sum=0;
for (int u = 0; u < newcols; u++)
{
//sum+=matrix1[i][u] * matrix2[u][j];
//tempMatrix[i][j]=sum;
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
}
}
}
for(int i = 0; i < newrows; i ++)
{
for (int j = 0; j < newcols; j++)
{
cout << tempMatrix[i][j] << " ";
}
cout << endl;
}
}
Initialize your first matrix like this:
matrix.resize(rows, vector<int>(cols,0));
and your second like this:
matrix2.resize(rows2, vector<int>(cols2,0));
where rows2 = cols. Note that there is no "multiplication rule" that implies cols2 == rows.
The problem is in your multiply_matrices function where the loops should be
for (int i = 0; i < rows; i++) // or matrix1.size()
for (int j = 0; j < cols2; j++) // or tempMatrix[i].size()
for (int u = 0; u < cols; u++) // or rows2 or matrix1[i].size()
but as already stated in the comments, it would be better to use vector::size() instead of passing the sizes as additional parameters.
Also, if you multiply (2x3)(3x2), the result is (2x2):
tempMatrix.resize(rows, vector<int>(cols2,0));
There is nothing wrong with the resize() function. What may be wrong is that you ignore the maximum size and rely solely on variables that are passed to your functions.
For example, your setMatrix function is passed rows and cols, but this is not necessary.
The function should be rewritten using only the matrix to provide the sizes to the loops:
void setMatrix(vector<vector<int> > &matrix)
{
int num;
for(int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix[i].size(); ++j)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j] = num;
}
cout << endl;
}
}
You have the same issue with multiply_matrix. What you should be doing is ensure that you're loops use the return value of vector::size(), which you do not do. The problem is here:
for (int i = 0; i < newrows; i++)
{
for (int j = 0; j < newcols; j++)
{
for (int u = 0; u < newcols; u++)
{
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
You sized the tempMatrix to newrows rows and newcols columns. But how do you know that matrix1 and matrix2 have at least newrows rows and newcols columns? You don't know, but you just assume they do.
So you either need to ensure that the size of matrix1 and matrix2 can accommodate the number of rows/columns, or you throttle those loops to use the minimum rows/columns.
Overall, the issue is that nowhere do you use vector::size() in your code that I see. So start to use size() to your advantage -- don't create superfluous (and possibly erroneously set) variables that supposedly denote the sizes of the rows and columns.