novice C++ programmer here (using Visual Studio 2013).
I'd like to write a function where I can insert a number, and it will check if that number has a zero directly above, below or beside it, and then return the position of the zero.
For example, if I want to check the surroundings of number 2 which is at (1, 1), I want it to return (if there is any) the position of 0 which is at (1, 2). How would I go about doing this? Should I use matrix field instead (int a[][] e.g.)?
The function will be used to determine if the number, say 2, is able to swap places with the another number (zero in my case), and it can only do so if the zero is directly above, below or beside it.
3 5 6 8
9 2 0 7
1 8 9 3
1 3 5 7
This is my code so far, it only creates a vector matrix (sorry if I'm using the incorrect terms), randomizes a number between 1 - 15 and places it at a (row, col), and then replaces a number in a chosen (row, col) with a zero with the function set_zero.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <vector>
using namespace std;
void set_zero(int row, int column, vector<vector<int>>& v){
v[row][column] = 0;
}
void scan_zero(vector<vector<int>>& v){
}
int _tmain(int argc, _TCHAR* argv[])
{
const int x = 4;
vector<vector<int>> v(x, vector<int>(x));
for (int i = 0; i < x; i++){
for (int j = 0; j < x; j++){
v[i][j] = rand() % 15 + 1;
}
}
set_zero(1, 2, v);
for (int i = 0; i < x; i++){
for (int j = 0; j < x; j++){
cout << setw(3) << v[i][j] << " ";
}
cout << endl;
}
}
I've tried searching the web for something similiar but I haven't found it, I'm sure it's out there but I just don't know how to properly formulate the search question.
Yeah, let's try using a 2d array (which simulates a matrix, int a[][] is referred to a 2d matrix).
Following your example: You want to check if the adjacent entries are zero. Let's use your example of (1,1) being 2.
A series of if statements could be your solution.
Let matrix be an integer 2d matrix of some size.
if matrix[1][2] equals 0 then return positionRight if matrix[1][0] equals 0 then return positionLeft if matrix[0][1] equals 0 then return positionUp if matrix[2][1] equals 0 then return positionDown
Since your you're only checking the indexes directly adjacent, 4 if statements isn't that bad of an idea to inspect for an adjacent zero.