http://www.geeksforgeeks.org/print-matrix-alternate-manner-left-right-right-left/
http://www.geeksforgeeks.org/form-coils-matrix/
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on).
void
convert(
int
arr[R][C])
{
bool
leftToRight =
true
;
for
(
int
i=0; i<R; i++)
{
if
(leftToRight)
{
for
(
int
j=0; j<C; j++)
printf
(
"%d "
, arr[i][j]);
}
else
{
for
(
int
j=C-1; j>=0; j--)
printf
(
"%d "
,arr[i][j]);
}
leftToRight = !leftToRight;
}
}
Given a positive integer n that represents dimensions of a 4n x 4n matrix with values from 1 to n filled from left to right and top to bottom. Form two coils from matrix and print the coils.
Examples:
Input : n = 1; Output : Coil 1 : 10 6 2 3 4 8 12 16 Coil 2 : 7 11 15 14 13 9 5 1 Explanation : Matrix is 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Total elements in matrix are 16n2. All elements are divided in two coils. Every coil has 8n2 elements. We make two arrays of this size. We first fill elements in coil1 by traversing in given order. Once we have filled elements in coil1, we can get elements of other coil2 using formula coil2[i] = 16*n*n + 1 -coil1[i].
void
printCoils(
int
n)
{
// Number of elements in each coil
int
m = 8*n*n;
// Let us fill elements in coil 1.
int
coil1[m];
// First element of coil1
// 4*n*2*n + 2*n;
coil1[0] = 8*n*n + 2*n;
int
curr = coil1[0];
int
nflg = 1, step = 2;
// Fill remaining m-1 elements in coil1[]
int
index = 1;
while
(index < m)
{
// Fill elements of current step from
// down to up
for
(
int
i=0; i<step; i++)
{
// Next element from current element
curr = coil1[index++] = (curr - 4*n*nflg);
if
(index >= m)
break
;
}
if
(index >= m)
break
;
// Fill elements of current step from
// up to down.
for
(
int
i=0; i<step; i++)
{
curr = coil1[index++] = curr + nflg;
if
(index >= m)
break
;
}
nflg = nflg*(-1);
step += 2;
}
/* get coil2 from coil1 */
int
coil2[m];
for
(
int
i=0; i<8*n*n; i++)
coil2[i] = 16*n*n + 1 -coil1[i];
// Print both coils
cout <<
"Coil 1 : "
;
for
(
int
i=0; i<8*n*n; i++)
cout << coil1[i] <<
" "
;
cout <<
"\nCoil 2 : "
;
for
(
int
i=0; i<8*n*n; i++)
cout << coil2[i] <<
" "
;
}