Tuesday, October 20, 2015

How to generate a CIRCULAR MATRIX using Multi-Dimensional Arrays

I have been asked to write a program for circular matrix in a interview programming round. 

Following program is a generic way of creating a circular matrix:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package blogspot.thinkwithjava;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 * @author R.D
 *
 */
class CircularMatrix {
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the number of elements : ");
  int n = Integer.parseInt(br.readLine());
  int A[][] = new int[n][n];
  int k = 1, c1 = 0, c2 = n - 1, r1 = 0, r2 = n - 1;
  while (k <= n * n) {
   for (int i = c1; i <= c2; i++) {
    A[r1][i] = k++;
   }
   for (int j = r1 + 1; j <= r2; j++) {
    A[j][c2] = k++;
   }
   for (int i = c2 - 1; i >= c1; i--) {
    A[r2][i] = k++;
   }
   for (int j = r2 - 1; j >= r1 + 1; j--) {
    A[j][c1] = k++;
   }
   c1++;
   c2--;
   r1++;
   r2--;
  }

  /* Printing the Circular Matrix */

  System.out.println("The Circular Matrix is:");
  for (int i = 0; i < n; i++) {
   for (int j = 0; j < n; j++) {
    System.out.print(A[i][j] + "\t");
   }
   System.out.println();
  }
 }
}

The output will look like this:




No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...