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

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎順列: FilterはPermutationの実装に使わなかったので削除
タグ: 2017年版ソースエディター
376 行
=== 順列・組合わせ ===
==== 順列 ====
;[https://go2goplay.golang.org/p/PoocwjTvCG5FtOGcqVIima 順列]:<syntaxhighlight lang="go" line>
package main
 
382 行
"fmt"
)
 
func Filter[T any](s []T, f func(T) bool) []T {
result := []T{}
for _, v := range s {
if f(v) {
result = append(result, v)
}
}
return result
}
 
func Permutation[T any](s []T, n int) [][]T {
421 ⟶ 411行目:
 
func main() {
fmt.Println(Filter([]int{1, 2, 3, 4, 5}, func(x int) bool { return x%2 == 0 }))
fmt.Println(Permutation([]int{1, 2, 3}, 1))
fmt.Println(Permutation([]int{0, 1, 2}, 2))
428 ⟶ 417行目:
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
[2 4]
[[1] [2] [3]]
[[1 0] [2 0] [0 1] [2 1] [0 2] [1 2]]