「Go/関数」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
→‎組合わせ: panic("Combination(): s == nil")
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎順列・組合わせ: 生成順序を修正
タグ: 2017年版ソースエディター
376 行
=== 順列・組合わせ ===
==== 順列 ====
;[https://go2goplay.golang.org/p/ELwv4XCz9N6D-c3QKnwqCd 順列]:<syntaxhighlight lang="go" line>
package main
 
import ("fmt"
 
"fmt"
var (
ErrNilSlice = fmt.Errorf("slice is nil")
)
 
func Permutation[T any](s []T, n int) (result [][]T) {
if s == nil {
panic("Permutation(): s == nil"ErrNilSlice)
}
result := [][]T{}
if n == 1 {
for _, v := range s {
result = append(result, []T{v})
}
return result
}
for i, v := range s {
sf := []T{}
for j, w := range s {
if j =!= i {
sf = append(sf, w)
continue
}
sf = append(sf, w)
}
for _, w := range Permutation(sf, n-1) {
result = append(result, append(w[]T{v}, vw...))
}
}
return result
}
 
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] [21 0] [0 1 2] [2 10] [0 2] [1 2]]
[[xyzabc def abcxyz] [defabc xyz abcdef] [xyzdef abc defxyz] [abcdef xyz defabc] [defxyz abc xyzdef] [abcxyz def xyzabc]]
panic: slice is nil
</syntaxhighlight>
;解説
425 ⟶ 427行目:
 
==== 組合わせ ====
;[https://go2goplay.golang.org/p/7T22aA-y1B82wS4Hj9-7h 組合わせ]:<syntaxhighlight lang="go" line>
package main
 
import ("fmt"
 
"fmt"
var (
ErrNilSlice = fmt.Errorf("slice is nil")
)
 
func Combination[T any](s []T, n int) (result [][]T) {
if s == nil {
panic("Combination(): s == nil"ErrNilSlice)
}
result := [][]T{}
if n == 1 {
for _, v := range s {
result = append(result, []T{v})
}
return result
}
for i, v := range s {
for _, w := range Combination(s[i+1:], n-1) {
result = append(result, append(w[]T{v}, vw...))
}
}
return result
}
 
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]]
[[1 0 1] [2 0] [2] [1 2]]
[[xyzabc def abcxyz]]
panic: slice is nil
</syntaxhighlight>
;解説