我正在尝试创建一个程序,该程序可以在四个方向上移动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
答案 0 :(得分:1)
我认为您进行正确旋转的代码是一个很好的草图,但是有几件事:
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
用于从较大的索引值迭代到较小的索引。