HOW TO PRINT OUT A STRING IN SPIRAL ORDER



HOW TO PRINT OUT A STRING IN SPIRAL ORDER 

//find the size of matrix and create an empty matrix;
dim = findMatrixSize(str);

//fill out "." at the end of string if string length<dim^2
fillString(str, dim);

//create matrix
createMatrix(matrix, dim);

//fill out matrix
fillMatrixInSpiral(matrix, str, 0, dim);

Assume that you already find out the dimension of a perfect square with the width a such that a^2>= str.length();

Describe this method:

We start from diagonal(11) or A1 as in the picture. 
If matrix has dimention=dim=width =N, then we will start reading the character from string and store to the matrix from Matrix[0,0] until Matrix[0,4] or A[1,1] until A[1,5]. 
Then continue this method but change direction as described in the picture. 
When we finish one round, we move the diagonal from M11 to M22(B2), update the new dimension of new square is dim-2. Why? Look at the picture we will see that, the width of the new square will be reduced by two units. 
We will continue this method until dim=1 or dim=0;
When dim=1, check the string if it is not empty. If it is not empty, then it is the last character in the string. So M[1][1]=str[last];
Why we need to check this? because there are two cases. when the length is odd, the last dim is 1; 
for example : 
Matrix dim =5
first square N=5
second square N =5-2=3
Last square N=3-2=1

Matrix dim =6
F Square N=6
S Square N=4
T Square N=2
Last Square N=0;

Following is the function fill a Matrix In Spiral Order


Comments

Popular posts from this blog

Morse Code Converter

CREDIT CARD NUMBER VALIDATOR