Golang 如何基于现有map生成一对多关系的映射结构
实现代码
package main import "fmt" type RateItem struct { RoomRateKey string `json:"room_rate_key"` Amount float64 `json:"amount"` } func GenerateRelationMap(input [][]RateItem) [][]RateItem { if len(input) < 2 || len(input[0]) == 0 { return nil } // 取下标为0的组作为基准组 baseGroup := input[0] // 剩余待组合的分组 otherGroups := input[1:] // 生成所有后续分组的下标笛卡尔积 indexCombos := [][]int{{}} for _, group := range otherGroups { var newCombos [][]int for _, combo := range indexCombos { for idx := range group { newCombo := append(append([]int{}, combo...), idx) newCombos = append(newCombos, newCombo) } } indexCombos = newCombos } // 生成最终结果 result := make([][]RateItem, 0, len(indexCombos)) for _, combo := range indexCombos { item := make([]RateItem, len(combo)) for i, idx := range combo { item[i] = baseGroup[idx] } result = append(result, item) } return result } func main() { // 测试数据,和示例输入规则对应 testInput := [][]RateItem{ // 下标为0的基准组 { {RoomRateKey: "0|0", Amount: 5307.84}, {RoomRateKey: "0|1", Amount: 5246.98}, }, // 下标为1的组,长度为2 make([]RateItem, 2), // 下标为2的组,长度为2 make([]RateItem, 2), } result := GenerateRelationMap(testInput) // 打印结果验证 for i, item := range result { fmt.Printf("[%d] => \n", i) for j, val := range item { fmt.Printf(" [%d] => room_rate_key: %s, amount: %.2f\n", j, val.RoomRateKey, val.Amount) } } }
运行上述代码输出的结构与期望结果完全匹配。
内容的提问来源于stack exchange,提问作者Bhargavi Pise
相关产品推荐
相关产品推荐

