Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spiral Pattern #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,4 +190,12 @@
* *
* *
* * * * * *
```
```
18. Spiral Pattern
```
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
```
98 changes: 98 additions & 0 deletions src/SpiralPattern/Spiral_Pattern.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import java.util.Scanner;

public class Spiral_Pattern
{
static void printSpiralPattern(int size)
{
//create two variables row and col to traverse rows and columns
int row = 0, col = 0;
int boundary = size - 1;
int sizeLeft = size - 1;
int flag = 1;
//variables r, l, u and d are used to determine the movement
// r = right, l = left, d = down, u = upper
char move = 'r';
//creating a 2D array for matrix
int[][] matrix =new int [size][size];
for (int i = 1; i < size * size + 1; i++)
{
matrix[row][col] = i;
//determining the next index
switch (move)
{
//if move = right, go right
case 'r':
col += 1;
break;
//if move = left, go left
case 'l':
col -= 1;
break;
//if move = up, go up
case 'u':
row -= 1;
break;
//if move = down, go down
case 'd':
row += 1;
break;
}
if (i == boundary)
{
//adding left size for the next boundary
boundary = boundary + sizeLeft;
//decreasing the size of left by 1, if 2 rotations have been made
if (flag != 2)
{
flag = 2;
}
else
{
flag = 1;
sizeLeft -= 1;
}
//rotating the movement
switch (move)
{
//if move = right, rotate to down
case 'r':
move = 'd';
break;
// if move = down, rotate to left
case 'd':
move = 'l';
break;
// if move = left, rotate to up
case 'l':
move = 'u';
break;
// if move = up, rotate to right
case 'u':
move = 'r';
break;
}
}
}

for (row = 0; row < size; row++)
{
for (col = 0; col < size; col++)
{
int n = matrix[row][col];
if(n < 10)
System.out.print(n +" ");
else
System.out.print(n +" ");
}
System.out.println();
}
}
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of array: \n");
int size = scanner.nextInt();
System.out.println("Spiral Matrix or Pattern is: \n");
printSpiralPattern(size);
}
}