Skip to content

Instantly share code, notes, and snippets.

@sampletext32
Created April 26, 2021 18:47
Show Gist options
  • Select an option

  • Save sampletext32/a6615077f758a6383a4e2a65c917deb7 to your computer and use it in GitHub Desktop.

Select an option

Save sampletext32/a6615077f758a6383a4e2a65c917deb7 to your computer and use it in GitHub Desktop.

Revisions

  1. sampletext32 created this gist Apr 26, 2021.
    71 changes: 71 additions & 0 deletions matrix.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    package com.company;

    import java.util.Scanner;

    public class Matrix {
    public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    String source = scanner.nextLine();

    int width = 3;
    int height = 3;

    int charsPerMatrix = width * height;
    int matricesCount = source.length() / charsPerMatrix + (source.length() % charsPerMatrix > 0 ? 1 : 0);

    char[][][] matrices = new char[matricesCount][height][width];

    for (int i = 0; i < matricesCount; i++) {
    int length = charsPerMatrix;
    if(i == matricesCount - 1)
    {
    length = source.length() % charsPerMatrix;
    }
    char[][] matrix = toMatrix(source, width, height, i * charsPerMatrix, length);
    matrices[i] = matrix;
    }

    for (int i = 0; i < matricesCount; i++) {
    printMatrix(matrices[i]);
    }
    }

    public static void printMatrix(char[][] matrix) {

    for (int i = 0; i < matrix[0].length * 4 + 1; i++) {
    System.out.print('-');
    }
    System.out.println();

    for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
    System.out.print("| " + (matrix[i][j] == '\0' ? " " : matrix[i][j]) + " ");
    }
    System.out.println("|");

    for (int j = 0; j < matrix[0].length * 4 + 1; j++) {
    System.out.print('-');
    }
    System.out.println();
    }
    System.out.println();
    }

    public static char[][] toMatrix(String src, int width, int height, int startIndex, int length) {
    char[][] chars = new char[height][width];

    int cell = 0;

    for (int i = startIndex; i < startIndex + length; i++) {
    int row = cell / width;
    int col = cell % width;

    chars[row][col] = src.charAt(i);
    cell++;
    }

    return chars;
    }
    }