「Go/関数」の版間の差分
削除された内容 追加された内容
→組合わせ: panic("Combination(): s == nil") タグ: 2017年版ソースエディター |
→順列・組合わせ: 生成順序を修正 タグ: 2017年版ソースエディター |
||
376 行
=== 順列・組合わせ ===
==== 順列 ====
;[https://go2goplay.golang.org/p/
package main
import
var (
ErrNilSlice = fmt.Errorf("slice is nil")
)
func Permutation[T any](s []T, n int) (result [][]T) {
if s == nil {
panic(
}
if n == 1 {
for _, v := range s {
result = append(result, []T{v})
}
return
}
for i, v := range s {
sf := []T{}
for j, w := range s {
if j
sf = append(sf, w)▼
}
▲ sf = append(sf, w)
}
for _, w := range Permutation(sf, n-1) {
result = append(result, append(
}
}
return
}
413 行
fmt.Println(Permutation([]int{0, 1, 2}, 2))
fmt.Println(Permutation([]string{"abc", "def", "xyz"}, 3))
fmt.Println(Permutation[int](nil, 2))
}
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
[[1] [2] [3]]
[[0 1] [0 2] [
[[
panic: slice is nil
</syntaxhighlight>
;解説
425 ⟶ 427行目:
==== 組合わせ ====
;[https://go2goplay.golang.org/p/
package main
import
var (
ErrNilSlice = fmt.Errorf("slice is nil")
)
func Combination[T any](s []T, n int) (result [][]T) {
if s == nil {
panic(
}
if n == 1 {
for _, v := range s {
result = append(result, []T{v})
}
return
}
for i, v := range s {
for _, w := range Combination(s[i+1:], n-1) {
result = append(result, append(
}
}
return
}
455 ⟶ 458行目:
fmt.Println(Combination([]int{0, 1, 2}, 2))
fmt.Println(Combination([]string{"abc", "def", "xyz"}, 3))
fmt.Println(Combination[int](nil, 2))
}
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
[[1] [2] [3]]
[[
[[
panic: slice is nil
</syntaxhighlight>
;解説
|