如何在F#中移动所有2D数组值(将它们包裹起来)



我正试图创建一个程序,将2D数组向四个方向移动。下面的示例向右移动。

1 0 0    0 1 0
0 2 0 -> 0 0 2
0 0 3    3 0 0

我真的不知道我在做什么,这是到目前为止的代码。请问,实现这一目标的最佳方式是什么?

open System
let mutable array = [| [| 1; 0; 0 |]
[| 0; 2; 0 |]
[| 0; 0; 3 |] |]
printfn "%A" array
for i in 0 .. (array.[*].Length - 1) do
for j in 0 .. (array.[*].[*].Length - 1) do
array.[i].[j] <- array.[(i + 1)].[(j + 1)]
printfn "%A" array
Console.Read() |> ignore

我认为你的右旋转代码是一个很好的草图,但有一些东西:

  • 如果使用数组的数组,则需要使用array.[i].Length获取长度
  • 您需要保存最后一个元素的值(进行旋转(
  • 您需要从右边迭代索引(如果您想将值移到右边(

这里有一段代码,用于右旋转:

for i in 0 .. array.Length - 1 do
// Save the last element in the array so that we can rotate it
let first = array.[i].[array.[i].Length-1]
// Iterate over elements from the rigth and put the value of
// element at index j into element at index j+1 (to the right)
for j in array.[i].Length - 2 .. -1 .. 0 do
array.[i].[j+1] <- array.[i].[j]
// We overwrote the last element in the array, so now we need to
// use the value we saved earlier for the first element
array.[i].[0] <- first

嵌套循环中的符号end .. -1 .. start用于从较大的索引值迭代到较小的索引值。

最新更新