From 4c1e3553036b5271a81af4d1fb47f7186704e578 Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Wed, 17 Jul 2024 23:04:12 +0200 Subject: [PATCH] Add: basic script that rotates a 2D slice clockwise --- rotateSlice.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 rotateSlice.go diff --git a/rotateSlice.go b/rotateSlice.go new file mode 100644 index 0000000..dd2d4dd --- /dev/null +++ b/rotateSlice.go @@ -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) +} +