如何在Java中將矩陣元素減一?
矩陣不僅僅是一個二維的矩形佈局中排列的資料元素的集合。在Java中,一個二維陣列可以被認為是一個矩陣。
根據問題陳述,我們需要從每個矩陣元素中減去一個元素“1”。
讓我們深入研究本文,瞭解如何使用Java程式語言來實現這一點。
舉幾個例子
示例-1
假設原始矩陣為{{3,1,2},{2,5,9},{6,3,10}};
在從給定矩陣中減去元素“1”後,結果索引將為−
2 0 1 1 4 8 5 2 9
示例-2
假設原始矩陣為{{2,1,9},{5,5,7},{3,6,10}};
在從給定矩陣中減去元素“1”後,結果索引將為−
1 0 8 4 4 6 2 5 9
演算法
步驟-1 − 宣告並初始化矩陣。
步驟-2 − 建立另一個矩陣來儲存加法值。
步驟-3 − 使用c[i][j] += a[i][j] - 1從矩陣中減去元素“1”。
步驟-4 − 列印結果。
多種方法
我們提供了不同方法的解決方案。
使用矩陣的靜態初始化
使用使用者定義的方法
讓我們逐一檢視程式及其輸出。
方法-1:使用三元運算子
在這種方法中,矩陣元素將在程式中初始化。然後根據演算法將矩陣元素減一。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising the matrix
int a[][]={{3,1,2},{2,5,9},{6,3,10}};
//creating another matrix to store the addition value
int c[][]=new int[3][3];
System.out.println("After decrementing each element by 1:");
//addition of element 1 to the matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]+=a[i][j] - 1;
//printing the result
System.out.print(c[i][j]+" ");
}
//new line
System.out.println();
}
}
}
輸出
After decrementing each element by 1: 2 0 1 1 4 8 5 2 9
方法-2:使用使用者定義的方法
在這種方法中,矩陣元素將在程式中初始化。然後透過將矩陣作為引數傳遞給使用者定義的方法,並在方法內部根據演算法將矩陣元素減一。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising the matrix
int arr[][]={{2,1,9},{5,5,7},{3,6,10}};
//calling user defined method
func(arr);
}
//user defined method
static void func(int[][] arr){
//creating another matrix to store the addition value
int c[][]=new int[3][3];
System.out.println("After decrementing each element by 1:");
//addition of element 1 to the matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]+=arr[i][j] - 1;
//printing the result
System.out.print(c[i][j]+" ");
}
//new line
System.out.println();
}
}
}
輸出
After decrementing each element by 1: 1 0 8 4 4 6 2 5 9
在這篇文章中,我們探索了使用Java程式語言將矩陣元素減一的不同方法。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP