Add: basic script that rotates a 2D slice clockwise
This commit is contained in:
parent
1f63795e49
commit
4c1e355303
1 changed files with 55 additions and 0 deletions
55
rotateSlice.go
Normal file
55
rotateSlice.go
Normal file
|
@ -0,0 +1,55 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// rotate90Clockwise rotates the given 2D slice 90 degrees clockwise
|
||||
func rotate90Clockwise(matrix [][]int) [][]int {
|
||||
n := len(matrix)
|
||||
if n == 0 {
|
||||
return matrix
|
||||
}
|
||||
m := len(matrix[0])
|
||||
|
||||
// Create a new 2D slice to hold the rotated matrix
|
||||
rotated := make([][]int, m)
|
||||
for i := range rotated {
|
||||
rotated[i] = make([]int, n)
|
||||
}
|
||||
|
||||
// Perform the rotation
|
||||
for i := 0; i < n; i++ {
|
||||
for j := 0; j < m; j++ {
|
||||
rotated[j][n-i-1] = matrix[i][j]
|
||||
}
|
||||
}
|
||||
|
||||
return rotated
|
||||
}
|
||||
|
||||
// printMatrix prints the 2D slice in a readable format
|
||||
func printMatrix(matrix [][]int) {
|
||||
for _, row := range matrix {
|
||||
fmt.Println(row)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Example 2D slice
|
||||
matrix := [][]int{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6},
|
||||
{7, 8, 9},
|
||||
}
|
||||
|
||||
fmt.Println("Original matrix:")
|
||||
printMatrix(matrix)
|
||||
|
||||
// Rotate the matrix
|
||||
rotatedMatrix := rotate90Clockwise(matrix)
|
||||
|
||||
fmt.Println("Rotated matrix:")
|
||||
printMatrix(rotatedMatrix)
|
||||
}
|
||||
|
Loading…
Reference in a new issue