Skip to content

Instantly share code, notes, and snippets.

@ermolnik
Last active April 15, 2019 06:40
Show Gist options
  • Save ermolnik/fe9e24ff8fe6e0cb95e2ea8c102f2ba2 to your computer and use it in GitHub Desktop.
Save ermolnik/fe9e24ff8fe6e0cb95e2ea8c102f2ba2 to your computer and use it in GitHub Desktop.
/**
* Created by ermolnik on 29.04.2018 15:38:12
*/
public class Main {
//matrix size
private static int size = 5;
//matrix initialization
private static int[][] n = new int[size][size];
//coordinates of matrix center
private static int dx = size / 2;
private static int dy = size / 2;
public static void main(String[] args) {
fillArray();
start();
}
//method for display matrix values by spiral
private static void start() {
System.out.println("");
System.out.print(n[dx][dy] + " ");
int i = 0;
while (!(dx == 0 && dy == 0)) {
i++;
left(i);
down(i);
i++;
right(i);
up(i);
}
}
//methods for move to some direction if it is possible
private static void left(int repeat) {
for (int i = 0; i < repeat; i++) {
if (dy > 0) {
dy--;
System.out.print(n[dx][dy] + " ");
}
}
}
private static void right(int repeat) {
for (int i = 0; i < repeat; i++) {
if (dy < size - 1 && !(dx == 0 && dy == 0)) {
dy++;
System.out.print(n[dx][dy] + " ");
}
}
}
private static void down(int repeat) {
for (int i = 0; i < repeat; i++) {
if (dx < size - 1 && !(dx == 0 && dy == 0)) {
dx++;
System.out.print(n[dx][dy] + " ");
}
}
}
private static void up(int repeat) {
for (int i = 0; i < repeat; i++) {
if (dx > 0 && dy != 0) {
dx--;
System.out.print(n[dx][dy] + " ");
}
}
}
//fill array with some values
private static void fillArray() {
int number = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
number++;
n[i][j] = number;
if (n[i][j] > 10) {
System.out.print(n[i][j] + " ");
} else System.out.print(n[i][j] + " ");
}
System.out.println("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment