JetBrains Academy: Multi dimensional array - Kamil-Jankowski/Learning-JAVA GitHub Wiki
Fill the matrix by numbers:
Given the number n, not greater than 100. Create the matrix of size n×n and fill it by the following rule. Numbers 0 should be stored on the primary diagonal. The two diagonals, adjacent to the primary one, should contain numbers 1. The next two diagonals - numbers 2, etc.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] matrix = new int[size][size];
// filling the matrix
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
matrix[i][j] = Math.abs(i-j);
}
}
// printing
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
System.out.printf("%d ", matrix[i][j]);
}
System.out.println();
}
}
}
Rotate a rectangle array:
Given a rectangle array n×m in size. Rotate it by 90 degrees clockwise, by recording the result into the new array m×n in size.
Input data format
Input the two numbers n and m, not exceeding 100, and then an array n×m in size.
Output data format
Output the resulting array. Separate numbers by a single space in the output.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
matrix[i][j] = scanner.nextInt();
}
}
int tmp = rows;
rows = columns;
columns = tmp;
int[][] rotatedMatrix = new int[rows][columns];
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
rotatedMatrix[i][j] = matrix[columns-1-j][i];
}
}
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.printf("%d ", rotatedMatrix[i][j]);
}
System.out.println();
}
}
}
Swap the columns:
Given a two-dimensional array (matrix) and the two numbers: i and j. Swap the columns with indexes i and j within the matrix.
Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indexes i and j.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int elementsInRow = scanner.nextInt();
int[][] matrix = new int[rows][elementsInRow];
for (int i = 0; i < rows; i++){
for (int j = 0; j < elementsInRow; j++){
matrix[i][j] = scanner.nextInt();
}
}
int index1 = scanner.nextInt();
int index2 = scanner.nextInt();
int[][] newMatrix = new int[rows][elementsInRow];
for (int i = 0; i < rows; i++){
for (int j = 0; j < elementsInRow; j++){
if (j == index1){
newMatrix[i][j] = matrix[i][index2];
} else if (j == index2){
newMatrix[i][j] = matrix[i][index1];
} else {
newMatrix[i][j] = matrix[i][j];
}
System.out.printf("%d ", newMatrix[i][j]);
}
System.out.println();
}
}
}
The star figure:
Given an odd number n, not exceeding 15. Create a two-dimensional array (matrix) from n×n elements, by filling it with "." symbols (each element of the matrix is a string containing a single symbol). Then fill the middle row of the matrix, the middle column, and the main and the secondary diagonals with the "" symbols. As a result, all ""s in the array must form the star figure. Output this matrix; elements of the array should be space separated.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final int size = scanner.nextInt();
char[][] star = new char[size][size];
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (i == j
|| i == size/2
|| j == size/2
|| i == size-1-j){
star[i][j] = '*';
} else {
star[i][j] = '.';
}
System.out.printf("%s ", star[i][j]);
}
System.out.println();
}
}
}
Cinema:
The cinema has n rows, each consisting of m seats (n and m do not exceed 20). The two-dimensional matrix stores the information on the sold tickets, number 1 means that the ticket for this place is already sold, the number 0 means that the place is available. You want to buy k tickets to the neighbouring seats in the same row. Find whether it can be done.
Input data format
On the input, the program gets the numbers n and m. Next go n lines, each containing m numbers (0 or 1), separated by spaces. Next goes the number k.
Output data format
The program should output the row number in which there are k consecutive available seats. If there are several such rows, output the number of the smallest such row. If there is no such row, output the number 0.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int seats = scanner.nextInt();
int[][] cinema = new int[rows][seats];
for (int i = 0; i < rows; i++){
for (int j = 0; j < seats; j++){
cinema[i][j] = scanner.nextInt();
}
}
int selectedAmount = scanner.nextInt();
int rowNumber = Integer.MAX_VALUE;
for (int i = 0; i < rows; i++){
for (int j = 0; j <= seats - selectedAmount; j++){
int emtySeatCounter = 0;
for (int k = 0; k < selectedAmount; k++){
if (cinema[i][j+k] == 0){
emtySeatCounter++;
}
}
if (emtySeatCounter == selectedAmount && i+1 < rowNumber){
rowNumber = i+1;
}
}
}
System.out.println(rowNumber != Integer.MAX_VALUE ? rowNumber : 0);
}
}
Spiral:
Output the matrix of size n×n, filled by the integers from 1 to n^2 in a spiral, coming from the top left corner and twisted clockwise.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
// filling-in the matrix
int[][] spiral = new int[size][size];
if (size % 2 != 0){ // for odd size
// ----- diagonals ----- //
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (i == size/2 && j == size/2){ // center
spiral[i][j] = (int) Math.pow(size, 2);
} else if (i+j == size-1 && i > size/2){ // lower left diagonal
if (i == size/2 + 1 && j == size/2 - 1){
spiral[i][j] = spiral[i-1][j+1] - 2;
} else {
spiral[i][j] = spiral[i-1][j+1] - 2 - 8 * ((i-size/2)-1);
}
} else if (i == j && i > size/2 && j > size/2){ // lower right diagonal
if (i == size/2 + 1 && j == size/2 + 1){
spiral[i][j] = spiral[i-1][j-1] - 4;
} else {
spiral[i][j] = spiral[i-1][j-1] - 4 - 8 * ((i-size/2)-1);
}
} else if (i+j == size-1 && i < size/2){ // upper right diagonal
if (i == 0){
spiral[i][j] = j+1;
} else {
spiral[i][j] = spiral[i-1][j+1] + 6 + 8 * ((j-size/2));
}
} else if (i == j && i < size/2 && j < size/2){ // upper left diagonal
if (i == 0){
spiral[i][j] = j+1;
} else {
spiral[i][j] = spiral[i-1][j-1] + 8 + 8 * ((size/2-j));
}
}
}
}
} else { // for even numbers
// ----- diagonals ----- //
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == size / 2 && j == size / 2 - 1) { // max
spiral[i][j] = (int) Math.pow(size, 2);
} else if (i == size / 2 && j == size / 2) {
spiral[i][j] = (int) Math.pow(size, 2) - 1;
} else if (i == size / 2 - 1 && j == size / 2) {
spiral[i][j] = (int) Math.pow(size, 2) - 2;
} else if (i == size / 2 - 1 && j == size / 2 - 1) {
spiral[i][j] = (int) Math.pow(size, 2) - 3;
} else if (i + j == size - 1 && i > size / 2) { // lower left diagonal
if (i == size / 2 + 1 && j == size / 2 - 2) {
spiral[i][j] = spiral[i - 1][j + 1] - 6;
} else {
spiral[i][j] = spiral[i - 1][j + 1] - 6 - 8 * ((i - size / 2) - 1);
}
} else if (i == j && i > size / 2 && j > size / 2) { // lower right diagonal
if (i == size / 2 + 1 && j == size / 2 + 1) {
spiral[i][j] = spiral[i - 1][j - 1] - 8;
} else {
spiral[i][j] = spiral[i - 1][j - 1] - 8 - 8 * ((i - size / 2) - 1);
}
} else if (i + j == size - 1 && i < size / 2) { // upper right diagonal
if (i == 0) {
spiral[i][j] = j + 1;
} else {
spiral[i][j] = spiral[i - 1][j + 1] + 10 + 8 * ((j - size / 2));
}
} else if (i == j && i < size / 2 && j < size / 2) { // upper left diagonal
if (i == 0) {
spiral[i][j] = j + 1;
} else {
spiral[i][j] = spiral[i - 1][j - 1] + 12 + 8 * ((size / 2 - 1 - j));
}
}
}
}
}
// ----- sides ----- //
for (int k = 0; k < size-2; k++){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (i != j && i+j != size-1){
if (i<j && i+j < size-1){ // top triangle
spiral[i][j] = spiral[i][j-1]+1;
} else if (i>j && i+j > size-1){ // bottom triangle
spiral[i][j] = spiral[i][j-1]-1;
} else if (i>j && i+j < size-1){ // left triangle
spiral[i][j] = spiral[i+1][j]+1;
} else if (i<j && i+j > size-1){ // right triangle
spiral[i][j] = spiral[i-1][j]+1;
}
}
}
}
}
// printing
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
System.out.printf("%d ", spiral[i][j]);
}
System.out.println();
}
}
}
or
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] spiral = new int[size][size];
int value = 1;
// defining boundaries
int minColumn = 0;
int minRow = 0;
int maxColumn = size-1;
int maxRow = size;
// filling-in the matrix
while (value <= size*size){
for (int i = minColumn; i < maxColumn+1; i++){
spiral[minRow][i] = value;
value++;
}
for (int i = minRow+1; i < maxRow; i++){
spiral[i][maxColumn] = value;
value++;
}
for (int i = maxColumn-1; i > minColumn; i--){
spiral[maxRow-1][i] = value;
value++;
}
for (int i = maxRow-1; i > minRow; i--){
spiral[i][minColumn] = value;
value++;
}
minRow++;
minColumn++;
maxColumn--;
maxRow--;
}
// printing
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
System.out.printf("%d ", spiral[i][j]);
}
System.out.println();
}
}
}
Sum of neighbours:
Write a program, which inputs the rectangular matrix from a sequence of lines, ending with a line, containing the only word "end" (without the quotation marks).
The program should output the matrix of the same size, where each element in the position (i, j)
is equal to the sum of the elements from the first matrix on the positions (i-1, j)
, (i+1, j)
, (i, j-1)
, (i, j+1)
. Boundary elements have neighbours on the opposite side of the matrix. In the case of one row or column, the element itself may be its neighbour.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String data = "";
int numberOfRows = 0;
int elementsInTheRow = 0;
while (scanner.hasNextLine()){
String tmp = scanner.nextLine();
if (tmp.contains("end")) {
break;
} else {
data = data.concat(tmp).concat(" ");
}
numberOfRows++;
}
// creating array of Strings
String[] array = data.split(" ");
// creating matrix of ints
elementsInTheRow = array.length / numberOfRows;
int[][] matrix = new int[numberOfRows][elementsInTheRow];
// filling the matrix with input
for (int i = 0; i < numberOfRows; i++){
for (int j = 0; j < elementsInTheRow; j++){
matrix[i][j] = Integer.parseInt(array[j+(i*elementsInTheRow)]);
}
}
// creating new matrix
int[][] neighbours = new int[numberOfRows][elementsInTheRow];
// filling neighbours matrix with calculated values
for (int i = 0; i < numberOfRows; i++){
for (int j = 0; j < elementsInTheRow; j++){
neighbours[i][j] = matrix[i][(j-1) < 0 ? j-1+elementsInTheRow : j-1] +
matrix[i][(j+1) >= elementsInTheRow ? j+1-elementsInTheRow : j+1] +
matrix[(i-1) < 0 ? i-1+numberOfRows : i-1][j] +
matrix[(i+1) >= numberOfRows ? i+1-numberOfRows : i+1][j];
}
}
// printing
for (int i = 0; i < numberOfRows; i++){
for (int j = 0; j < elementsInTheRow; j++){
System.out.printf("%d ",neighbours[i][j]);
}
System.out.println();
}
}
}
Symmetric matrix:
Given the number n, not exceeding 10, and a matrix of size n × n.
Check whether this matrix is symmetric in relation to the main diagonal. Output the word “YES”, if it is symmetric and the word “NO” otherwise.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final int size = scanner.nextInt();
int[][] matrix = new int[size][size];
boolean symmetric = true;
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
matrix[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (matrix[i][j] != matrix[j][i]){
symmetric = false;
break;
}
}
}
System.out.println(symmetric ? "YES" : "NO");
}
}
Maximum element in a matrix:
Find the indexes of the initial appearance of the maximum element in a matrix.
Input data format:
On the input, the program receives the size of matrix n and m, and then n lines having m integer numbers in each. n and m do not exceed 100.
Output data format:
Output two numbers: the row number and the column number, in which the greatest item in the two-dimensional array (matrix) is located. If there are several such elements, output the one, which has the smaller row number; and if row numbers are the same - the one having the smaller column number.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
int max = Integer.MIN_VALUE;
String coordinates = "";
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
matrix[i][j] = scanner.nextInt();
if (matrix[i][j] > max){
max = matrix[i][j];
coordinates = String.format("%d %d", i, j);
}
}
}
System.out.println(coordinates);
}
}
Check Sudoku:
N-size sudoku is a game with a square table of N^2 width and height divided into N^2 smaller squares of N width and height. In a solved state, each of this smaller squares, as well as each row and column of a full square, contains all numbers from 1 to N^2 without repetition.
Given a number N on the first line and a full sudoku table on the next N^2 lines. Every line contains N^2 integers.
Your task is to determine whether this sudoku is solved or not. Output "YES" if this sudoku table is solved, otherwise "NO".
N can be from 1 to 10.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] sudoku = new int[size * size][size * size];
// scanning the input game field
for (int i = 0; i < sudoku.length; i++) {
for (int j = 0; j < sudoku[i].length; j++) {
sudoku[i][j] = scanner.nextInt();
}
}
// writing section block into rows in new array
int[][] blocks = new int[size*size][size*size];
int rowNumber=0;
int columnNumber=0;
for (int i = 0; i < blocks.length-size+1; i+=size){
for (int j = 0; j < blocks.length-size+1; j+=size){
for (int k = i; k < i+size; k++){
for (int l = j; l < j+size; l++){
blocks[rowNumber][columnNumber] = sudoku[k][l];
columnNumber++;
}
}
rowNumber++;
columnNumber=0;
}
}
// defining conditions and fields
boolean uniqueValuesInRows = false;
boolean uniqueValuesInColumns = false;
boolean uniqueValuesInBlocks = false;
boolean checking = true;
int iterator = 0;
// checking all three conditions
while (iterator < sudoku.length && checking) {
// checking rows
String row = Arrays.toString(sudoku[iterator]);
for (int j = 0; j < sudoku[iterator].length; j++) {
if (row.contains(String.valueOf(j + 1))) {
uniqueValuesInRows = true;
} else {
uniqueValuesInRows = false;
checking = false;
break;
}
}
// checking columns
String column = "";
for (int j = 0; j < sudoku[iterator].length; j++) {
column = column.concat(String.format("%d ", sudoku[j][iterator]));
}
if (column.contains(String.valueOf(iterator + 1))) {
uniqueValuesInColumns = true;
} else {
uniqueValuesInColumns = false;
checking = false;
break;
}
// checking square blocks
String block = Arrays.toString(blocks[iterator]);
for (int j = 0; j < blocks[iterator].length; j++) {
if (block.contains(String.valueOf(j + 1))) {
uniqueValuesInBlocks = true;
} else {
uniqueValuesInBlocks = false;
checking = false;
break;
}
}
iterator++;
}
//printing
System.out.println(uniqueValuesInRows && uniqueValuesInColumns && uniqueValuesInBlocks ? "YES" : "NO");
}
}
Pretty looking pattern:
In some design style, a 4x4 matrix pattern is considered looking pretty if it doesn't consist of a 2x2 matrix of the same color. Your task is to write the program that outputs "YES" if the 4x4 matrix is looking pretty, otherwise output "NO".
Input contains 4 lines, each line contains 4 symbols, different symbols represent different colors: W stands for white color, B - black, R - red, G - green, Y - yellow.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] pattern = new char[4][4];
boolean pretty = true;
for (int i = 0; i < pattern.length; i++){
pattern[i] = scanner.nextLine().toCharArray();
}
for (int i = 0; i < pattern.length-1; i++){
for (int j = 0; j < pattern.length-1; j++){
if (pattern[i][j] == pattern[i+1][j] && pattern[i][j] == pattern[i][j+1] && pattern[i][j] == pattern[i+1][j+1]){
pretty = false;
i = pattern.length;
break;
}
}
}
System.out.println(pretty ? "YES" : "NO");
}
}