Given a n*n matrix and a value k, how do we find all the neighbors for each element?
for example: in a 4*4 matrix, with k=2
say matrix is :
[ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16]
where these values are the indexes of the location, the neighbors for 1 are 1,2,3,5,6,9 . The values 3,6 and 9 come only because k =2 and wouldnt be there if k was = 1.
similarly the neighbors of 6 will be 1 2 3 5 6 7 8 9 10 11 and 14
Can you please help me to write a c code to implement this in c++.
It is the problem of von Neumann neighborhood, please can some one implement it in c++. Thanks
Your neighbors will form a diamond pattern around your target element. The points of the diamond will be k hops away from the target element. So the top will be k rows up, the left will be k columns over, etc. The diamond expands uniformly as you go from level to level. If you start at the top point and go one row down (closer to the target node) then you go out 1 to each side. It's symmetric in the other directions. In other words, the difference in x coordinates between a neighbor and the target node plus the difference in y will be <= k.
So just make two nested for loops that iterate over this diamond. Outer loop iterates over the rows, inner loop over the columns. Start at the top then expand the diamond by 1 at each outer loop iteration until you reach the same row as the target element, then contract until you reach the bottom point.
Obviously you'll need to test boundary conditions for going outside the matrix.
This should do the trick for k=1. Make minor changes to make it work for all k
int width = 4;
int height = 4;
int k = 1;
int value = 2;
bool hasRight = (value % width != 0);
bool hasLeft = (value % width != 1);
bool hasTop = (value > 4);
bool hasBottom = (value < (height * width - width));
cout << value; // Always itself
if(hasRight == true) {
cout << value+1 << " "; // Right
if(hasTop == true) {
cout << value-width << " " << value-width+1 << " "; // Top and Top-right
}
if(hasBottom == true) {
cout << value+width << " " << value+width+1; // Bottom and Bottom-right
}
}
if(hasLeft == true) {
cout << value-1 << " "; // Left
if(hasTop == true) {
cout << value-width-1 << " "; // Top-left
}
if(hasBottom == true) {
cout << value+width-1 << " "; // Bottom-left
}
}
Related
I am trying to traverse a 2D matrix diagonally and the function below prints all elements in a diagonal.I want to skip the first row and first column elements and start the diagonal traversal from matrix[1][1] because the values in the 0th row and 0th column are not required.So it is like slicing the matrix from the top and starting from [1][1] but not making any changes to the bottom of the matrix.
void diagonalOrder(int matrix[][COL])
{
for(int line = 1;
line <= (ROW + COL - 1);
line++)
{
int start_col = max(0, line - ROW);
int count = min(line, (COL - start_col), ROW);
/* Print elements of this line */
for(int j = 0; j < count; j++)
cout << setw(5) <<
matrix[minu(ROW, line) - j - 1][start_col + j];
cout << "\n";
}
I will update my question with an example to make it clear.Consider the following matrix.
0 1 2 3 4
matrix[5][5] = 1 8 5 3 1
2 4 5 7 1
3 6 4 3 2
4 3 4 5 6
The above function will print the values of this diagonally.
Output:
0
1 1
2 8 2
3 4 5 3
4 6 5 3 4
3 4 7 1
4 3 1
5 2
6
I want to skip the elements of the first row and the first column and starting at matrix[1][1] want to traverse the matrix diagonally.
Desired Output:
8
4 5
6 5 3
3 4 7 1
4 3 1
5 2
6
From your example it looks like you want to print antidiagonals not diagonals, ie third line is 3 4 5 3 not 3 5 4 3.
To get started keep things simple: Indices (i,j) along an antidiagonal are those i and j where i+j == some_constant. Hence this is a simple (not efficient) way to print elements along one antidiagonal:
void print_antidiagonal(int matrix[5][5],int x){
for (int i=4;i >= 0; --i) {
for (int j=0;j < 5; ++j) {
if (i+j == x) std::cout << matrix[i][j] << " ";
}
}
std::cout << "\n";
}
Further there are nrows + (ncols-1) antidiagonals, hence you can print them all via:
for (int i=0;i < 5+4; ++i) {
print_antidiagonal(matrix,i);
}
The function above isnt very efficient, but it is simple. It is obvious how to skip the first row and first column:
for (int i=4;i >= 1; --i) { // loop till 1 instead of 0
for (int j=1;j < 5; ++j) { // loop from 1 instead of 0
This is sufficient to produce desired output (https://godbolt.org/z/7KWjb7qh7). However, not only is the above rather inefficient, but also the code is not very clear about its intent. print_antidiagonal prints elements along a single anti-diagonal, hence iterating all matrix elements is a bad surprise.
I suggest to print the indices rather than the matrix elements to get a better picture of the pattern (https://godbolt.org/z/TnrbbY4jM):
1,1
2,1 1,2
3,1 2,2 1,3
4,1 3,2 2,3 1,4
4,2 3,3 2,4
4,3 3,4
4,4
Again, in each line i+j is a constant. And that constant increments by 1 in each line. In each line i decrements while j increments, until either i == 1 or j==4. The first element is such that i is maximum and j = constant - i.
Hence:
void print_antidiagonal(int matrix[5][5],int x){
int i = std::min(x-1,4);
int j = x - i;
while (i >= 1 && j <= 4) {
std::cout << matrix[i][j] << " ";
--i;
++j;
}
std::cout << "\n";
}
Live Example.
PS: I used hardcoded indices, because I considered it simpler to follow the logic. For a more realistic solution the matrix size and offset should be parametrized of course.
I don't really get what your code is trying to do but just going by the description you need to iterate over the array items with equal row and column indices until there either are no more rows or no more columns i.e.
void print_tail_of_diagonal(int matrix[ROWS][COLS])
{
int n = std::min(ROWS, COLS);
for (int i = 1; i < n; ++i) {
std::cout << matrix[i][i] << " ";
}
std::cout << "\n";
}
The CSES problem Josephus Problem I requires us to print the sequence of how people are chosen for n people and k = 2. I found an elegant solution to this here.
Basically, the code is similar to this:
void J(int n)
{
int a = 1, b = 0;
while (n > 0)
{
for (int i = 2; i <= n; i += 2)
{
cout << a * i + b << ' ';
}
if (n & 1)
cout << a + b << ' ', b += a;
else
b -= a;
a <<= 1;
n >>= 1;
}
}
Can someone explain why it works?
I made a few changes to the code to illustrate how it works.
void J(int n)
{
int a = 1, b = 0;
while (n > 0)
{
std::cout << "n=" << n << std::endl;
std::cout << "a=" << a << ", b=" << b << std::endl;
for (int i = 2; i <= n; i += 2)
{
std::cout << a * i + b << ' ';
}
if (n & 1) // equivalent to n % 2 == 1 (if n is odd)
std::cout << '*' << a + b << ' ', b += a;
else
b -= a;
std::cout << std::endl;
a <<= 1; // a = a * 2;
n >>= 1; // n = n / 2;
}
}
The first thing to note is that the variables a and b are initialized to values that allow us to compute the positions of people who will be eliminated as we go around the circle (also using the iterator i in the for loop). The initial values of a = 1, b = 0 are so we can eliminate every even numbered person on the first iteration.
Next, every time through the while(n) loop, half of the remaining people will be eliminated. If n is odd, we loop back to the beginning of the circle and also eliminate the person at the start of the current iteration.
I think the tricky part here is how the values of a and b change in the if statement. If n is odd we increment b by the value of a. If n is even we subtract the value of a from b. Then we double the value of a to get ready for the next iteration around the circle. The values of a and b are chosen to account for the gaps in the circle left by eliminating positions in the previous iterations.
Finally, we divide n by 2 before the next iteration, since there are half as many people left in the circle. Here's a sample run for n=19.
Output:
n=19
a=1, b=0
2 4 6 8 10 12 14 16 18 *1
n=9
a=2, b=1
5 9 13 17 *3
n=4
a=4, b=3
11 19
n=2
a=8, b=-1
15
n=1
a=16, b=-9
*7
Write a C++ program to find the number of pairs of integers in a given array of integers whose sum is equal to a specified number. The program will ask the user to input 10 numbers and check if a pair of integers will be equal to a user-specified number.
Your program will show the location of the pair of integers in the array and their corresponding values.
SAMPLE INPUT:
Enter an array of integers: 75 90 100 32 1 55 92 123 56 10
Sum of pairs of integers: 101
SAMPLE OUTPUT:
The location of the pair of integers are number[2] and number[4] and the values are
100 and 1, respectively
Depending on how you'd like to implement it, you could consider a recursive approach similar to this:
void pairAddToK(vector<int> L, int left, int right, int K) {
if (left == right) // Our base case
return;
if (left + 1 == right) { // 2 elements, check if they add to K
if (L[left] + L[right] == K)
cout << L[left] << " + " << L[right] << " = " << K << endl;
}
int mid = (left + right) / 2; // General case, use recursion to divide and conquer
pairAddToK(L, left, mid, K);
pairAddToK(L, mid + 1, right, K);
for (int i = left; i <= mid; i++) // Check for pairs from both halves
for (int j = mid + 1; j <= right; j++)
if (L[i] + L[j] == K)
cout << L[i] " + " << L[j] << " = " << K << endl;
}
Something along these lines should work. I did not test this and wrote this only inside the StackOverflow answer box, so let me know if this needs clarity.
You will need a nested while loop or nested for-loop.
check if arr[0] + arr[1] == sum_of_pair_of_int
if it is, insert it into the pair... an array can work too.
then check if arr[0] + arr[2].
repeat for rest of array.
then start at arr[1] + arr[2], then arr[1] + arr[3], etc.
If you have a more specific question, that would be more helpful.
I am trying to write a backtracking algorithm for harmonious graph coloring (no adjacent colors can be the same, and also each pair of colors can appear only once).
This is the backtracking function:
void Graph::colorBacktrack(int a, int b) {
print();
for (int i = 1; i <= colors; i++) //assigning colors until match
{
elems[a][b] = i; //color
if (check(a, b)) break; //if it's alright break
if (i == colors) // if all the colors have been used -
return; //return one stack back and look again
}
int nextA;
int nextB = b;
if (a < size - 1 ) nextA = a + 1;
else {
nextA = 0;
nextB = b + 1;
}
if (a == size && b == size - 1) //when array is complete - cout finished
{
cout << endl << endl << "Finished" << endl << endl;
}
colorBacktrack(nextA, nextB); //go to next node when everything is fine
}
checking is working properly and all the other things. The problem is that the output is wrong - at the end it shows something like this:
1 4 2 6
2 5 7 8
3 6 4 8
<--- this is wrong
1 7 3 0
<--- this is also wrong
So when it cannot find a solution in current tree it just ends everything instead of going up. Why is it happening?
I am looking for an algorithm that numbers and outputs a triangle with sides n (or half of a square) where n is an input of the program. But the numbering starts at the top of the triangle, goes down the diagonal, back along the bottom row and up the left edge. If there is an interior remaining it goes diagonally down from the highest number and continues.
Here is an example:
1
9 2
8 10 3
7 6 5 4
Here is my code and it results in:
1
10 2
9 8 3
7 6 5 4
Is there any algorithm for this of program if there any please explain to me.
The above program works well with row size less than 3 but doesn't for size above 3.
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i,j,v=0;
static int k;
clrscr();
cout<<"Enter the number of rows : ";
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
v++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<i;j++)
{
cout<<v;
cout<<"\t";
v--;
}
while(k==i)
{
k++;
cout<<k;
cout<<"\t";
}
cout<<"\n";
}
getch();
}
Here's a solution that doesn't use any array storage. The spiral can be thought of as a set of right angled triangles inside each other. The function iterates over all the rows and columns and for each position, it calculates what triangle the element is on by finding the closest distance to the edge of the outer triangle, then computes its adjusted position (x, y) relative to the top-left corner of that inner triangle, the number of rows of the inner triangle (r), and the start number of the inner triangle (start+1). Then it outputs a number based on whether it lies on the diagonal, horizontal or vertical side.
#include <iostream>
#include <iomanip>
using namespace std;
int main(void) {
int rows;
cout << "Enter the number of rows : ";
cin >> rows;
int i, j;
for(i = 0; i < rows; i++)
{
for(j = 0; j <= i; j++)
{
// find the closest side:
int distance = j; // distance to vertical side
if(i-j < distance)
distance = i-j; // distance to diagonal side
if((rows-1)-i < distance)
distance = (rows-1)-i; // distance to horizontal side
int r = rows - distance * 3;
// compute position on inner triangle:
int x = j - distance;
int y = i - distance * 2;
// compute start number for inner triangle:
int start = (((rows+1)*rows)/2) - (((r+1)*r)/2);
// output number based on side:
if(x==y) // diagonal side
cout << setw(2) << (start+y+1) << " ";
else if(y==(r-1)) // horizontal side
cout << setw(2) << (start+(r*2)-(x+1)) << " ";
else // vertical side
cout << setw(2) << (start+(r*3)-(y+2)) << " ";
}
cout << endl;
}
return 0;
}
Demo
Take the example where rows equals 7. In that case the distance value for each element will be:
(0)
0 0
0 (1) 0
0 1 1 0
0 1 (2) 1 0
0 1 1 1 1 0
0 0 0 0 0 0 0
All elements with the same distance value form a triangle. The number of rows of the outer triangle is 7, the next smaller one has 4, then 1. So r = rows - (distance * 3).
The top-left corner of the outer triangle is at row 0, column 0. The first inner triangle is row 2, column 1, the next one is at row 4, column 2. So the position of a given row/column position on the inner triangle that it lies on is found by subtracting distance * 2 from the row and distance from the column, so y = i - (distance *2) and x = j - distance.
The inner triangle column is stored in x. The inner triangle row is stored in y. In the example above, the values in brackets are the top-left corners of each triangle, where x = 0 and y = 0. For example for the top-left corner of the triangle with distance = 1, i = 2 and j = 1, so x = 1 - 1 = 0, and y = 2 - (1 * 2) = 0.
The start value is found by calculating the number of elements in the entire large triangle ((row+1)*row)/2 and then subtracting the number of elements remaining, which is the number of elements in the inner triangle.
For a triangle with n rows, the total number of elements is ((n+1)*n)/2, as shown below for rows = 5:
1 X 0 0 0 0 0
2 X X 0 0 0 0
3 X X X 0 0 0
4 X X X X 0 0
5 X X X X X 0
1 2 3 4 5 6
To count the number of X's, we can see that it's half the number of elements in a rectangle of (5+1)*5, so half of 30, which is 15.
If there are 2 triangles one inside the other, like this:
X
X X
X O X
X O O X
X X X X X
and we want to count the number of X's, then we can calculate the size of the entire triangle using the above formula to get 15, and then calculate the size of the inner triangle which has 2 rows as ((2+1)*2)/2 = 3, and subtracting the smaller from the larger gives 15 - 3 = 12. So if there are 12 X's, then the first O must be number 13. That's how we can calculate the number to output for the top-left corner of the inner triangle.
Once you've calculated all that it's just a matter of working out which side of the inner triangle the element is on and printing it out.
Here is a general idea as to how to solve this with recursion. There is probably a way to solve this in a space-efficient way, but I leave that for someone else. So let's say we store this as an array of arrays accessed by x[i][j] and let's say the size of sides of the triangle are n. You can google for how to dynamically create an array of arrays.
Now what we want is an equation for the outside of the triangle. Numbers along the diagonal are (i(i+1))/2 for 1 <= i <= n. Numbers along the left edge are 1+(i(i-1))/2 for 1 <= i <= n. And numbers along the bottom are 1+(n(n-1))/2 .. (n(n+1))/2.
So now to the recursion. Let j be the size of the remaining triangle yet to be numbered, k the highest number you've encountered before and (l,m) the index of the top of the triangle. Use the equations above and the preceding information to calculate the number and store that into the remaining triangle array. If there is yet another interior, recurse with the highest number and index of the top. And so on.
Example for side size 4. First number the outside. Highest prior number is 0. Index of the first position is (0,0)
1
9 2
8 x 3
7 6 5 4
We are not done because we still have an interior of size one. So when you recurse you, the position of the top of the triangle is (2,2), the highest number so far is 9 and the size of the triangle remaining is 1.
Now try with side size 5. After the first numbering we'd get:
1
12 2
11 x 3
10 x x 4
9 8 7 6 5
And the triangle remaining also starts at (2,2) as for side 4. But the size of the triangle remaining is now 2 and the highest number seen so far is 12.
After all the recursion is done, then print out of the table.
Easy way is to use an array.
#include <iostream>
using namespace std;
int main(){
int n;
cout <<"Enter the number of rows : ";
cin >> n;
int **tri = new int *[n];
for(int i=0; i<n; i++){
tri[i] = new int[i+1];
}
int v = 0, r = 0, c = 0;
for(int k = n-1; 0 <= k; k -=3){//k is total side size / 3, next k -2 -1
if(k==0){
tri[r][c] = ++v;
break;
}
for(int i = 0; i < k; ++i)//↘
tri[r++][c++] = ++v;
for(int i = 0; i < k; ++i)//←
tri[r][c--] = ++v;
for(int i = 0; i < k; ++i)//↑
tri[r--][c] = ++v;
r += 2; ++c;//next start position
}
//print
for(r = 0; r < n; ++r){
for(c = 0; c <= r; ++c)
cout << tri[r][c] << '\t';
cout << endl;
}
for(int i=0; i<n; i++){
delete[] tri[i];
}
delete[] tri;
}