Created
April 13, 2023 20:10
-
-
Save kitlabcode/319b230ec2fff14f1bb61437c622b611 to your computer and use it in GitHub Desktop.
copy slice and append - used to build permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // You can edit this code! | |
| // Click here and start typing. | |
| package main | |
| import "fmt" | |
| type Item struct { | |
| name string | |
| number int | |
| } | |
| func (it *Item) copy() *Item { | |
| return &Item{ | |
| name: it.name, | |
| number: it.number, | |
| } | |
| } | |
| func main() { | |
| names := []string{"a", "b"} | |
| numbers := []int{1, 2} | |
| items := []*Item{} | |
| for _, name := range names { | |
| item := &Item{name: name} | |
| items = append(items, item) | |
| } | |
| for n, i := range numbers { | |
| if n > 0 { | |
| fmt.Println(n, "make a copy of the items") | |
| itemCopies := make([]*Item, len(items)) | |
| copy(itemCopies, items) | |
| for j := 0; j < len(items); j++ { | |
| itemCopies[j] = items[j].copy() | |
| } | |
| fmt.Println(n, "set the numbers on the copies") | |
| for _, item := range itemCopies { | |
| item.number = i | |
| } | |
| fmt.Println(n, "append the copies to the original") | |
| items = append(items, itemCopies...) | |
| } else { | |
| fmt.Println(n, "first pass set all the items to the first number") | |
| for _, item := range items { | |
| item.number = i | |
| } | |
| } | |
| } | |
| for n, i := range items { | |
| fmt.Printf("%d %+v\n", n, *i) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment