Java 程式顯示上三角矩陣
在本文中,我們將瞭解如何在 Java 中顯示給定矩陣的上三角矩陣。矩陣是其元素的行和列排列。具有 m 行和 n 列的矩陣可以稱為 m × n 矩陣。並且,術語上三角矩陣指的是所有對角線以下的元素均為 0 的矩陣。
示例場景
Input: matrix = { 2, 1, 4 },
{ 1, 2, 3 },
{ 3, 6, 2 }
Output: upptri_mat = 2 1 4
0 2 3
0 0 2
使用巢狀 for 迴圈
要顯示給定矩陣的上三角矩陣,請使用巢狀 for 迴圈迭代矩陣的每個元素。然後,使用行 != 列條件將 0 分配給矩陣對角線以下的所有 [i][j] 位置。
示例
在下面的 Java 程式中,我們使用巢狀 for 迴圈來列印上三角矩陣。
public class UpperTriangle {
public static void main(String[] args) {
int input_matrix[][] = {
{ 2, 1, 4 },
{ 1, 2, 3 },
{ 3, 6, 2 }
};
int rows = input_matrix.length;
int column = input_matrix[0].length;
System.out.println("The matrix is defined as: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
if (rows != column) {
return;
} else {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
if (i > j) {
input_matrix[i][j] = 0;
}
}
}
System.out.println("The upper triangular matrix is: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
}
}
}
執行此程式碼後,您將獲得以下結果:
The matrix is defined as: 2 1 4 1 2 3 3 6 2 The upper triangular matrix is: 2 1 4 0 2 3 0 0 2
使用 Java 流
在這種方法中,我們使用巢狀的 IntStream.range() 方法而不是 for 迴圈 來迭代矩陣的每個元素。對於每個元素,如果其行索引大於其列索引(即對角線以下),則列印“0”。否則,列印元素的值。
示例
在這個 Java 程式中,我們使用 Java 流來顯示上三角矩陣。
import java.util.Arrays;
import java.util.stream.IntStream;
public class UpperTriangle {
public static void main(String[] args) {
int[][] input_matrix = {
{ 2, 3, 6 },
{ 1, 2, 2 },
{ 1, 4, 2 }
};
int rows = input_matrix.length;
int column = input_matrix[0].length;
System.out.println("Given Matrix: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("The upper triangular matrix is: ");
IntStream.range(0, input_matrix.length).forEach(i -> {
IntStream.range(0, input_matrix[i].length)
.mapToObj(j -> j < i ? "0" : String.valueOf(input_matrix[i][j]))
.forEach(n -> System.out.print(n + " "));
System.out.println();
});
}
}
程式碼輸出如下:
Given Matrix: 2 3 6 1 2 2 1 4 2 The upper triangular matrix is: 2 3 6 0 2 2 0 0 2
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP