c++ - Identifying the nth inserted element of matrix which fills by inserting alternating upper and lower triangle elements -
i trying write function able map nth inserted element matrix (i,j) position. known method filling matrix, doing in following way non-standard way.
(0,0)...(0,1)...(1,0)...(0,2)...(2,0)...(n,0)...(0,n)... (1,1)....(1,2)...(2,1)...(n,1)...(1,n) .....(n,n)
in other words starts @ top left, , after inserting diagonal element, inserts alternating elements upper , lower triangle way across outter row & column, rinses , repeats steps 1 row / 1 column in.
and trying achieve function
std::pair<int,int> getmatrixcoordinates (int nthelement) { return std::pair<int,int> (row, col) ; }
this merely takes bit of programming:
template <int n> std::pair<int, int> getmatrixcoordinates(int i) { int a(n - std::sqrt(n * n - i)); int b(i - (2 * n - a) * a); int c(a + (b + 1) / 2); return std::make_pair(b & 1? a: c, b & 1? c: a); }
Comments
Post a Comment