JavaRush /Java Blog /Random EN /Solving problems involving one-dimensional and two-dimens...
Анзор Кармов
Level 31
Санкт-Петербург

Solving problems involving one-dimensional and two-dimensional arrays

Published in the Random EN group
This article will consider (and, to a greater extent, provide for independent analysis) problems involving arrays. We will improve our skills in the following areas:
  1. One-dimensional arrays

    1. Problems “Continue the sequence” ;
    2. Element search tasks;
    3. Problems involving sorting array elements.
  2. Two-dimensional arrays

    1. Tasks “Construct a matrix of the form” ;
    2. Tasks “Find elements in the most unexpected places (rows, columns, diagonals)” ;
    3. Tasks “Arrange the ships for a water battle . ”
For all problems we will use arrays of integers. We solve problems on one-dimensional and two-dimensional arrays - 1

Problems involving one-dimensional arrays

Continue the sequence

In this series of tasks you will need to:
  1. Determine the pattern according to which this or that numerical sequence is formed.
  2. Write a function that forms the first N elements of a given sequence as an integer array and displays the array elements on the screen.
Suppose we are faced with the task of continuing the following number series:

1, 2, 3, 4, 5…
Step 1: Identify the pattern. Everything here is elementary - it’s a series of natural numbers. Step 2: write a function that will form the first N elements of a given row as an array:
public class Main {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(createArrayOfIntegers(10)));

        // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }

    public static int[] createArrayOfIntegers(int n) {
        int[] array = new int[n];
        for (int i = 1; i <= n; i++) {
            array[i-1] = i;
        }

        return array;
    }
}
Similarly, it is necessary to write functions that would continue the following sequences:

A. 2,  4,  6,   8,  10...
B. 1,  3,  5,   7,   9...
C. 1,  4,  9,  16,  25...
D. 1,  8, 27,  64, 125...
E. 1, -1,  1,  -1,   1,  -1...
F. 1, -2,  3,  -4,   5,  -6...
G. 1, -4,  9, -16,  25....
H. 1,  0,  2,   0,   3,   0,  4....
I. 1,  2,  6,  24, 120, 720...
J. 1,  1,  2,   3,   5,   8, 13, 21…

Search for elements

In this series of tasks, it is necessary to find an element in the finished array that has some properties. For example, the element with the maximum value. To demonstrate, let's write the code for a function that takes an array and determines the index of the maximum element in the array, and then outputs this element along with its index to the console. I will also demonstrate how, using the class, java.util.concurrent.ThreadLocalRandomyou can quickly generate an integer array of a given length, consisting of random elements:
public class Main {

    public static void main(String[] args) {
        int[] array = generateRandomIntArray(10);
        findMax(array);

        /*
        Output:
        Generated random array: [50551934, -551646189, 410352642, 1822778873, -1744293692, -1140287711, 878876868, -2116893120, -797503442, -703924530]
        Max element is [1822778873] with index [3]
        */

    }


    public static int[] generateRandomIntArray(int n) {
        int[] array = ThreadLocalRandom.current().ints().limit(n).toArray();
        System.out.println("Generated random array: " + Arrays.toString(array));
        return array;
    }

    public static void findMax(int[] array) {
        int maxIndex = 0;
        int max = array[maxIndex];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
                maxIndex = i;
            }
        }

        System.out.println(String.format("Max element is [%d] with index [%d]", max, maxIndex));
    }
}
Now the tasks themselves. From an array of random integer elements we need to find:
  1. Maximum.
  2. Minimum.
  3. Average.
  4. The number of elements between the maximum and minimum elements.
  5. The first prime number.
  6. The last prime number.
  7. The number of prime numbers in the array.
You can display both the value and the indices. If there is no element you are looking for, display it on the screen as you wish. For the last task, you need to prepare an array of integer elements sorted in ascending order. In this array, you need to find an element by value in a minimum number of operations ( Hint ).

Sorting

In this series of problems, you need to sort an array of integer elements using various sorting algorithms. There are quite a lot of materials on the Internet on various algorithms. Try to understand the essence of the algorithm first, and then try to implement it yourself. First on paper (block diagram, pseudocode, whatever suits you), and then in IDEA. Algorithms for implementation:
  • bubble sort;
  • selection sort;
  • insertion sort;
  • merge sort.

Problems involving two-dimensional arrays

Draw the matrix

In the next series of tasks, it is necessary to draw (output to the console) two-dimensional arrays (matrices) composed in a certain way: they must correspond to the pattern specified by the task. Let me give you an example. We need to build and display a matrix m*n(where mis the number of rows, and nis the number of elements in the row) of the form:

1, 2, 3, 4
5, 6, 7, 8
9,10,11,12
Let's write a function that will do everything for us, and also provide a function that will beautifully output the matrix to the console (you may find it useful):
public class Main {

    public static void main(String[] args) {
        createAndDrawMatrix(3, 4);

    }

    public static void createAndDrawMatrix(int m, int n) {
        int[][] matrix = new int[m][n];

        int value = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = value;
                value ++;
            }
        }

        printMatrix(matrix);
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] array : matrix) {
            for (int anInt : array) {
                System.out.print(String.format("%3d", anInt));
            }
            System.out.println();
        }
    }
}
Now tasks: Display a matrix m*nof the form: 4, 3, 2, 1 8, 7, 6, 5, 12,11,10, 9 ----------- 1, 4, 7 2, 5, 8 3, 6, 9 ----------- 9, 8, 7 6, 5, 4 3, 2, 1 ----------- 12,11,10, 9 8, 7, 6, 5, 4, 3, 2, 1

Search for elements

In this section, it is necessary to implement a search for various elements in different parts of the matrix: in a specific column or in a specific row. Let's assume we have a matrix of the form: -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 As an example, let's find the number of negative elements in the third row:
public class Main {

    public static void main(String[] args) {
        int [][] 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}
        };

        findNegativeCountInRow(matrix, 3);
    }

    private static void findNegativeCountInRow(int[][] matrix, int rowNumber) {
        int negativeCount = 0;
        for (int element : matrix[rowNumber]){
            if (element < 0) {
                negativeCount ++;
            }
        }

        System.out.println("Matrix: ");
        printMatrix(matrix);
        System.out.println(String.format("Has %d negative elements in #%d row ", negativeCount, rowNumber));

    }

    public static void printMatrix(int[][] matrix) {
        for (int[] array : matrix) {
            for (int anInt : array) {
                System.out.print(String.format("%5d", anInt));
            }
            System.out.println();
        }
    }
}
As a result of executing the main method, the following will be output to the console:

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
Has 3 negative elements in #3 row 
Now the tasks. For any odd, nprint a matrix n*nof the form:

1,  -2,  3,  
-4,  5, -6,
7,  -8,  9
From this matrix derive:
  • all negative elements;
  • all negative elements in the string i;
  • all negative elements in the column j;
  • all diagonal elements (starting from the upper left corner);
  • all diagonal elements (starting from the lower left corner).

Sea battle

Last section with an asterisk: no tips or examples. Matrices are ideal for programming the game of sea battle. One of the stages of programming this game is the placement of ships on the playing field. If you solve a number of these problems, rest assured that you will be able to cope with naval combat. So, given a 10x10 matrix consisting of zeros. Let's assume that it is a field for playing naval battle. In this field, 0 is an empty cell, 1 is a ship or part of a ship. Write functions, each of which, according to the rules of the sea battle game, places them randomly:
  • 10 single-deck ships;
  • 10 double-deck corbals;
  • 5 three-decker ships;
  • arranges all the ships for the game of sea battle (4 single-deck, 3 double-deck, 2 three-deck, 1 four-deck).
That's all! As with any programming topic, arrays are best learned through practice. Happy warm-up!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION