Skip to content

Instantly share code, notes, and snippets.

@spiegel-im-spiegel
Last active November 16, 2018 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spiegel-im-spiegel/cb39570730d300d570ad739efc82bf41 to your computer and use it in GitHub Desktop.
Save spiegel-im-spiegel/cb39570730d300d570ad739efc82bf41 to your computer and use it in GitHub Desktop.
日能研の問題をGo言語で力づくで解いてみた(2018/11) ref: https://qiita.com/spiegel-im-spiegel/items/90332789f8a6f98c670d
package main
import "fmt"
func Permutations(cards []int) <-chan []int {
ch := make(chan []int)
go func() {
defer close(ch)
perm(ch, make([]int, 0, len(cards)), cards)
}()
return ch
}
func dup(list []int) []int {
l := make([]int, len(list), cap(list))
copy(l, list)
return l
}
func perm(ch chan<- []int, list []int, rest []int) {
if len(rest) == 0 {
ch <- dup(list)
return
}
for i, v := range rest {
restx := dup(rest)
restx = append(restx[:i], restx[i+1:]...)
listx := append(list, v)
perm(ch, listx, restx)
}
}
func list2num(list []int) int {
v := 0
for i, t := len(list)-1, 1; i >= 0; i, t = i-1, t*10 {
v += list[i] * t
}
return v
}
func main() {
for p := range Permutations([]int{1, 2, 3, 4, 5, 6}) {
res := true
for i := 2; i <= 6; i++ {
if list2num(p[:i])%i != 0 {
res = false
break
}
}
if res {
fmt.Println(list2num(p))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment