👪
[Go]slice→二次元slice
Go slice → 二次元slice
intの例
package main
import "fmt"
func main() {
fmt.Println(to2D(makeSlice(12), 0))
fmt.Println(to2D(makeSlice(30), 6))
fmt.Println(to2D(makeSlice(40), 6))
fmt.Println(to2D(makeSlice(37), 8))
}
func makeSlice(n int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
res[i] = i
}
return res
}
func to2D(s []int, n int) [][]int {
res := make([][]int, 0)
if len(s) == 0 || n == 0 {
return res
}
c := len(s) / n
loop := c
if len(s)%n != 0 {
loop += 1
}
for i := 0; i < loop; i++ {
tmp := make([]int, 0)
for j := 0; j < n; j++ {
idx := i*n + j
if idx == len(s) {
break
}
tmp = append(tmp, s[idx])
}
if len(tmp) != 0 {
res = append(res, tmp)
}
}
return res
}
output
[]
[[0 1 2 3 4 5] [6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29]]
[[0 1 2 3 4 5] [6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29] [30 31 32 33 34 35] [36 37 38 39]]
[[0 1 2 3 4 5 6 7] [8 9 10 11 12 13 14 15] [16 17 18 19 20 21 22 23] [24 25 26 27 28 29 30 31] [32 33 34 35 36]]
Genericsの例
1.18から追加されたGenericsを使って書き直すと、嬉しい
package main
import "fmt"
func main() {
fmt.Println(anyTo2D(makeStringSlice("abcdefghijklmnopqrstuvwxyz"), 5))
fmt.Println(anyTo2D(makeRuneSlice("abcdefghijklmnopqrstuvwxyz"), 6))
}
func makeStringSlice(s string) []string {
dist := make([]string, 0)
for _, r := range s {
dist = append(dist, string(r))
}
return dist
}
func makeRuneSlice(s string) []rune {
dist := make([]rune, 0)
for _, r := range s {
dist = append(dist, r)
}
return dist
}
func anyTo2D[G any](s []G, n int) [][]G {
res := make([][]G, 0)
if len(s) == 0 || n == 0 {
return res
}
c := len(s) / n
loop := c
if len(s)%n != 0 {
loop += 1
}
for i := 0; i < loop; i++ {
tmp := make([]G, 0)
for j := 0; j < n; j++ {
idx := i*n + j
if idx == len(s) {
break
}
tmp = append(tmp, s[idx])
}
if len(tmp) != 0 {
res = append(res, tmp)
}
}
return res
}
output
[[a b c d e] [f g h i j] [k l m n o] [p q r s t] [u v w x y] [z]]
[[97 98 99 100 101 102] [103 104 105 106 107 108] [109 110 111 112 113 114] [115 116 117 118 119 120] [121 122]]
Discussion