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程序。

Open Compiler
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)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

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])的元素,并显示修改后的矩阵。

结论

这就是我们如何交换给定矩阵的首行和尾行元素的方法。此方法适用于任何类型的矩阵,例如方阵、对称矩阵、横向矩阵等。

更新于:2022年12月29日

227 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告