Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- public class Snippet {
- private final static Scanner s = new Scanner(System.in);
- private final static Random r = new Random();
- public static void main(String[] args) throws Exception {
- print("Enter grid size: ");
- // read grid size
- int n = s.nextInt();
- // spacing
- println();
- // make square grid
- int[][] g = new int[n][n];
- // iterate over indicies in grid, set the value.
- for (int y = 0; y < n; y++) {
- for (int x = 0; x < n; x++) {
- // set value at y:x, then print it
- print(g[y][x] = r.nextInt(2));
- }
- println();
- }
- // spacing
- println();
- // find rows with same values
- for (int y = 0; y < n; y++) {
- // initial value in row-y.
- int row = g[y][0];
- String rowStr = String.valueOf(row);
- String line = rowStr;
- // check and see if value of 'row' changes.
- for (int x = 1; x < n; x++) {
- // if same, add to 'rowStr'
- // if different make 'rowStr' null so we will not add to it
- if (row == g[y][x] && line != null) {
- // same content
- line += rowStr;
- } else {
- // failed
- line = null;
- }
- }
- // print row string if not null
- if (line != null) {
- println("Row[" + (y + 1) + "]: " + line);
- }
- }
- // spacing
- println();
- // find columns with same values
- // this is mostly the same as the last block of code, but with x/y
- // switched.
- for (int x = 0; x < n; x++) {
- // initial value in col-y.
- int col = g[0][x];
- String colStr = String.valueOf(col);
- String line = colStr;
- // check and see if value of 'col' changes.
- for (int y = 1; y < n; y++) {
- // if same, add to 'colStr'
- // if different make 'colStr' null so we will not add to it
- if (col == g[y][x] && line != null) {
- // same content
- line += colStr;
- } else {
- // failed
- line = null;
- }
- }
- // print column string if not null
- if (line != null) {
- println("col[" + (x + 1) + "]: " + line);
- }
- }
- // spacing
- println();
- // diagonal-1: top-left --> bottom-right
- int d1 = g[0][0];
- String d1Str = String.valueOf(d1);
- String d1Line = d1Str;
- // diagonal-2: top-right --> bottom-left
- int d2 = g[0][n - 1];
- String d2Str = String.valueOf(d2);
- String d2Line = d2Str;
- for (int d = 1; d < n; d++) {
- // check diagonal 1,
- if (g[d][d] == d1 && d1Line != null) {
- d1Line += d1Str;
- } else {
- d1Line = null;
- }
- // check diagonal 2,
- if (g[d][(n-1)-d] == d2 && d2Line != null) {
- d2Line += d2Str;
- } else {
- d2Line = null;
- }
- }
- // print diagonals
- if (d1Line != null) println("Diagonal-Forwards: " + d1Line);
- if (d2Line != null) println("Diagonal-Backward: " + d2Line);
- }
- private static void println() { System.out.println(); }
- private static void println(Object x) { System.out.println(x); }
- private static void print(Object x) { System.out.print(x); }
- }
Advertisement
Add Comment
Please, Sign In to add comment