Swift程式:交換矩陣首尾行的元素
在這篇文章中,我們將學習如何編寫一個Swift程式來交換矩陣中首行和尾行的元素。因此,為了交換元素,我們需要將給定矩陣的首行元素與尾行元素互換。例如:
Original matrix: 2 4 5 6 3 4 6 2 6 7 7 2 1 1 1 1 So after swapping the first and last rows we get: 1 1 1 1 3 4 6 2 6 7 7 2 2 4 5 6
演算法
步驟1 - 建立一個函式。
步驟2 - 使用for迴圈迭代每個元素。
步驟3 - 交換首列和尾列的元素。
let temp = mxt[0][x] mxt[0][x] = mxt[size-1][x] mxt[size-1][x] = temp
步驟4 - 建立一個矩陣。
步驟5 - 呼叫函式並將矩陣作為引數傳遞。
步驟6 - 列印輸出。
示例
以下是交換矩陣首尾行元素的Swift程式。
import Foundation
import Glibc
// Size of the array
var size = 3
// Function to interchange the elements
// of first and last rows
func FirstLastInterchange(M:[[Int]]){
var mxt : [[Int]] = M
// Interchanging the elements of first
// and last rows by swapping
for x in 0..<size{
let temp = mxt[0][x]
mxt[0][x] = mxt[size-1][x]
mxt[size-1][x] = temp
}
// Displaying matrix
print("Matrix after first and last rows interchange:")
for m in 0..<size{
for n in 0..<size{
print(mxt[m][n], terminator: " ")
}
print("\n")
}
}
// Creating 3x3 matrix of integer type
var myMatrix : [[Int]] = [[11, 33, 44],
[55, 66, 77],
[88, 33, 22]]
print("Original Matrix:")
for x in 0..<size{
for y in 0..<size{
print(myMatrix[x][y], terminator:" ")
}
print("\n")
}
// Calling the function
FirstLastInterchange(M:myMatrix)
輸出
Original Matrix: 11 33 44 55 66 77 88 33 22 Matrix after first and last rows interchange: 88 33 22 55 66 77 11 33 44
在上面的程式碼中,我們有一個3x3的方陣。我們建立一個函式,其中我們使用for迴圈從0迭代到size-1,對於每次迭代,我們使用臨時變數交換首行(mxt[0][x])和尾行(mxt[size-1][x])的元素,並顯示修改後的矩陣。
結論
這就是我們如何交換給定矩陣的首行和尾行元素的方法。此方法適用於任何型別的矩陣,例如方陣、對稱矩陣、橫向矩陣等。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP