Java 找到矩阵每行的最小元素
在Java中,数组是一个对象。它是一种非基本数据类型,用于存储相同数据类型的值。在Java中,矩阵实际上是一个多维数组,表示多行和多列。
根据问题的陈述,我们需要找到给定矩阵中每行的最小元素,这个矩阵是一个多维数组。
让我们深入探讨一下这篇文章,了解如何使用Java编程语言来实现。
为了向你展示一些实例
实例-1
Suppose the original matrix is = {
{2, 3,11, 4, 6},
{21,12,32,45,2},
{41,12,3,45, 2}
}
行0中的最小元素为1
行1中的最小元素为2
行2中的最小元素为2
实例-2
Suppose the original matrix is = {
{2, 3, 1, 4, 6},
{21, 12, 32, -4, 2},
{4, 12, 3, 45, 2},
{-12, -13, 6, 1, 8}
}
在第0行中,最小的元素是1
在第1行中,最小的元素是-4
在第2行中,最小的元素是2
在第3行中,最小的元素是-13
实例-3
Suppose the original matrix is = {
{2, 3, 1},
21,12,32},
{4,12,13}
}
第0行中的最小元素为1
第1行中的最小元素为12
第2行中的最小元素为4
步骤
步骤1 - 声明并初始化一个整数多维数组。
步骤2 - 使用循环迭代给定矩阵的行。
步骤3 - 在该循环内使用另一个循环来迭代列,通过这种方法,我们现在可以通过所有的行中的可用元素。
步骤4 -我们通过条件将这些行的元素传递以获得最小值。
步骤5 - 在每次循环中获得最小值后,我们将这些值与其相应的行索引作为输出打印出来。
语法
要获取数组的长度(数组中的元素数),有一个内置的数组属性即 length
以下是其语法-
array.length
其中,’array’指的是数组引用。
多种方法
我们提供了不同的方法来解决问题。
- 通过使用静态初始化数组元素
-
通过使用用户定义的方法
让我们逐个查看程序及其输出。
方法1:通过使用静态初始化数组元素
在这种方法中,数组元素将在程序中进行初始化。然后根据算法,将打印矩阵每一行的最小值作为输出。
示例
public class Main{
public static void main(String[] args) {
//declare an integer type multi dimentional array
//here we take a 3X3 Matrix with some random values
int[][] inputMatrix = {
{21,34,76},
{2,1,5},
{90,23,-23}
};
for (int r = 0; r < inputMatrix.length; r++) {
int minimumValue = inputMatrix[r][0];
for (int c = 0; c < inputMatrix[r].length; c++){
//if the current index value is smaller than the Minimum value
if (inputMatrix[r][c] < minimumValue) {
//store the minimum value to the variable each time
//when the above condition satisfied
minimumValue = inputMatrix[r][c];
}
}
//print the row index value along with the derived minimum value
System.out.println("The minimum element present in row-" + r + " is " + minimumValue);
}
}
}
输出
The minimum element present in row-0 is 21
The minimum element present in row-1 is 1
The minimum element present in row-2 is -23
方法2: 使用用户自定义的方法
在这种方法中, 数组元素将在程序中初始化。然后通过将数组作为参数调用一个用户定义的方法, 并且根据算法, 将矩阵每行的最小值作为输出。
示例
public class Main {
public static void main(String[] args) {
//declare an integer type multi dimentional array
//a 3X3 Matrix with some random values
int[][] inputMatrix ={
{2, 3, 1},
{21,12,32},
{4,12,3}
};
//call the user-defined method
Min(inputMatrix);
}
//user defined method
public static void Min(int[][] mat) {
for (int r = 0; r < mat.length; r++) {
int minimumValue = mat[r][0];
//initiate the loop to check through the columns
for (int c = 0; c < mat[r].length; c++){
//if the current index value is smaller than the Minimum value
if (mat[r][c] < minimumValue) {
//store the minimum value to the variable each time
//when the above condition satisfied
minimumValue = mat[r][c];
}
}
//print the row index value along with the derived minimum value
System.out.println("The minimum element present in row-" + r + " is " + minimumValue);
}
}
}
输出
The minimum element present in row-0 is 1
The minimum element present in row-1 is 12
The minimum element present in row-2 is 3
在本文中,我们使用Java编程语言探索了不同的方法来找到矩阵中每行的最小元素。