'Merging 2 slices from a method into a map
I have a function that returns 2 variables in a form of slices and I want to merge the two slices into a map as key-value pairs. The issue is that can't find a way to iterate through each slice separately and add them as a key and a value. The current implementation is iterating through all the prices and it's adding every price to the town key.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
cities, prices := citiesAndPrices()
towns := groupSlices(cities, prices)
for cities := range towns {
fmt.Println(cities, prices)
}
}
func citiesAndPrices() ([]string, []int) {
rand.Seed(time.Now().UnixMilli())
cityChoices := []string{"Berlin", "Moscow", "Chicago", "Tokyo", "London"}
dataPointCount := 100
cities := make([]string, dataPointCount)
for i := range cities {
cities[i] = cityChoices[rand.Intn(len(cityChoices))]
}
prices := make([]int, dataPointCount)
for i := range prices {
prices[i] = rand.Intn(100)
}
return cities, prices
}
func groupSlices([]string, []int) map[string]int {
cities, prices := citiesAndPrices()
towns := make(map[string]int)
for _, cities := range cities {
for _, prices := range prices {
towns[cities] = prices
break
}
}
return towns
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
