1
0
Fork 0

Add: basic script that rotates a 2D slice clockwise

This commit is contained in:
Aroy-Art 2024-07-17 23:04:12 +02:00
parent 1f63795e49
commit 4c1e355303
Signed by: Aroy
GPG key ID: 583642324A1D2070

55
rotateSlice.go Normal file
View 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)
}