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

We solve problems on one-dimensional and two-dimensional arrays

Published in the Random EN group
This article will consider (and to a greater extent, given for independent analysis) tasks on arrays. We will develop our skills in the following areas:
  1. One-Dimensional Arrays

    1. Tasks “Continue the sequence” ;
    2. Tasks for finding elements;
    3. Tasks for sorting array elements.
  2. 2D arrays

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

Problems on 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 the given sequence as an integer array and displays the elements of the array on the screen.
Suppose we are faced with the task of continuing the following number series:

1, 2, 3, 4, 5…
Step 1: identify a pattern. Everything is elementary here - this is 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, you need 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 maximum value element. 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 prints 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 element.
  5. First prime number.
  6. The last prime number.
  7. The number of primes in the array.
You can output both value and indexes. If there is no element you are looking for, display it on the screen as you see fit. 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 the minimum number of operations ( Hint ).

Sorting

In this series of tasks, it is necessary to sort an array of integer elements using various sorting algorithms. There are quite a lot of materials on the network 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 you like), and then in IDEA. Algorithms for implementation:
  • bubble sort;
  • selection sorting;
  • insertion sort;
  • merge sort.

Problems on 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 given by the task. I'll 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 per 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 give a function that will beautifully display the matrix to the console (maybe it will come in handy for you):
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 the m*nview matrix: 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, you need to implement a search for different elements in different parts of the matrix: in a specific column or in a specific row. Suppose 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 displayed in 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 tasks. For any odd noutput 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).
We solve problems on one-dimensional and two-dimensional arrays - 2

sea ​​battle

Last section with an asterisk: no hints or examples. Matrices are ideal for programming the sea battle game. One of the stages of programming this game is the placement of ships on the playing field. If you solve a number of these tasks, be sure that the sea battle is tough for you. So, given a 10x10 matrix consisting of zeros. Suppose that it is a field for the game of naval combat. 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 game, the sea battle arranges in a random way:
  • 10 single-deck ships;
  • 10 two-deck corbals;
  • 5 three-deck ships;
  • arranges all ships for playing naval combat (4 single-deck, 3 double-deck, 2 three-deck, 1 four-deck).
That's all! As with any topic in programming, arrays are best dealt with by doing. Happy workout!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION