Generating the numbers and displaying the matrix in the consoles are not working well.



  • Started to meet this challenge:

    Dana is a complete Mx N size matrix. Find the last one of its lines containing the maximum number of the same elements.

    I created a code, but when a compilation takes place, the chiel generation is filled with zeros, and the matrix in the consoles is misleading. Can you help me find a mistake and fix the code right?

    import java.util.Random;
    

    public class Main {

    public static void main(String[] args) {
    Random rnd = new Random(); // Создаём экземпляр генератора случайных чисел(будем заполнять матрицу случайными числами)
    int n = 8, m = 9; // Объявляем константы для задания размерности матрицы
    int [][]matrix = new int[n] [m]; // Создаём матрицу размерностью NxM
    int i, j, z, temp1 = 1, temp2 = 1, maxi = -1; // Объявлем целочисленные переменные
    System.out.println("Рандомная матрица:");
    for (i = 0; i < n; i++)
    {
    for (j = 0; j < m; j++)
    {
    matrix[i] [j] = (int) Math.random()*10; // В цикле присваиваем каждому элементу матрицы случайное число
    System.out.println("{0} "+ matrix[i] [j]); // И сразу же выводим его в консоль
    }
    System.out.println();
    }
    for (i = 0; i < n; i++)
    {
    for (j = 0; j < m-1; j++)
    {
    z = j+1;
    // В цикле сравниваем элемент matrix[i, j] с последующими в данной строке, если нашли одиноковый увеличиваем счётчик temp1 на единицу(количество одиноковых элементов)
    while (z < m)
    {
    if (matrix[i] [j] == matrix[i] [z])
    {
    temp1++;
    }
    z++;
    }
    }
    // Если в данной строке одинаковых элементов больше чем в предыдущих запоминаем индекс данной строки
    if (temp1 > temp2)
    {
    temp2 = temp1;
    maxi = i;
    }
    temp1 = 1;
    }
    // Вывод ответа с индексом строки содержащей максимальное количество одинаковых элементов
    if (maxi == -1)
    {
    System.out.println("Строк с одинаковыми элементами не существует");
    }
    else
    {
    System.out.println("Индекс строки с максимальным количеством одиноковых элементов: {0}" + maxi);
    }
    System.out.println();
    }
    }

    Что выходит



  • Math.random() generates numbers from 0 to 1 (not including 1) e.g.
    0.777328667250996
    0.49824728555371

       matrix[i] [j] = (int) Math.random()*10; 
    

    (int) Math.random()*10 will always be 0.

    Try that. (int) (Math.random() * 10)

    created a rand and you don't use it. Random rnd = new Random();

    rnd.nextInt(2) 2 numbers - 0.1
    rnd.nextInt(10)10 numbers - 0 to 9 (including)
    (rnd.nextInt(10)+1) - 1 to 10 (including)



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2