Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- int c;
- do{
- System.out.println("1. Горизонтальная 2. Вертикальная 3. По спирали 0. Выход");
- System.out.print("Ваш выбор ");
- c=sc.nextInt();
- if (c!=0){
- System.out.println("Задайте размер массива N ");
- int n=sc.nextInt();
- switch (c){
- case 1: print(horizontal(n)); break;
- case 2: print(vertical(n)); break;
- case 3: print(spiral(n)); break;
- }
- }
- } while (c!=0);
- }
- static int [][] horizontal(int n){
- int a[][]=new int [n][n];
- int i=0, j=0, dj=1;
- for (int k=1; k<=n*n; k++){
- a[i][j]=k;
- j=j+dj;
- if (j==n || j==-1) {
- dj*=-1;
- i++;
- j+=dj;
- }
- }
- return a;
- }
- static int [][] vertical(int n){
- int a[][]=new int [n][n];
- int i=0, j=0, dj=1;
- for (int k=1; k<=n*n; k++){
- a[j][i]=k;
- j=j+dj;
- if (j==n || j==-1) {
- dj*=-1;
- i++;
- j+=dj;
- }
- }
- return a;
- }
- static void print(int b[][]){
- for (int i=0; i<b.length; i++){
- for (int j=0; j<b[i].length; j++)
- System.out.print(b[i][j]+"\t");
- System.out.println();
- }
- }
- static int [][] spiral(int n){
- int a[][]=new int [n][n];
- int i=0, j=n-1;
- int value = n*n;
- while (n != 0){
- int k = 0;
- do {a[i][j--] = value--;} while (++k < n-1);
- for (k = 0; k <n-1;k++) a[i++][j] = value--;
- for (k = 0; k <n-1;k++) a[i][j++] = value--;
- for (k = 0; k <n-1;k++) a[i--][j] = value--;
- ++i; --j; n = n < 2 ? 0: n-2;
- }
- return a;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement