/* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:15 # User : geovindu # Product : GoLand # Project : goalgorithms # File : const.go */ package common const ( CaratDecimal 3 MoneyDecimal 2 EPS 1e-6 ) /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:15 # User : geovindu # Product : GoLand # Project : goalgorithms # File : error.go */ package common import fmt // 基础业务错误 type GemBaseError struct { Msg string } func (e *GemBaseError) Error() string { return fmt.Sprintf(珠宝配石异常: %s, e.Msg) } // 参数非法 func NewGemParamInvalidError(msg string) error { return GemBaseError{Msg: fmt.Sprintf(参数非法: %s, msg)} } // 预算为0/负数 func NewBudgetZeroError() error { return GemBaseError{Msg: 预算必须大于0} } // 库存为空 func NewStockEmptyError() error { return GemBaseError{Msg: 宝石库存为空无法配石} } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:16 # User : geovindu # Product : GoLand # Project : goalgorithms # File : util.go */ package common import math // 克拉保留3位小数 func RoundCarat(val float64) float64 { mul : math.Pow10(CaratDecimal) return math.Round(val*mul) / mul } // 金额保留2位小数 func RoundMoney(val float64) float64 { mul : math.Pow10(MoneyDecimal) return math.Round(val*mul) / mul } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:16 # User : geovindu # Product : GoLand # Project : goalgorithms # File : gem_entity.go */ package entity import goalgorithms/greedy/common // GemStone 库存宝石实体映射数据库 type GemStone struct { StoneName string json:stone_name TotalCarat float64 json:total_carat BatchPrice float64 json:batch_price } // UnitCaratValue 单位预算对应克拉性价比排序依据 func (g *GemStone) UnitCaratValue() float64 { return g.TotalCarat / g.BatchPrice } // GemAllocateItem 单款宝石配石明细 type GemAllocateItem struct { StoneName string json:stone_name UseCarat float64 json:use_carat UseCost float64 json:use_cost } // GemAllocateResultDTO 对外标准返回DTO对齐Python输出结构 type GemAllocateResultDTO struct { BudgetTotal float64 json:预算总额 CostActual float64 json:实际花费 BudgetRemain float64 json:剩余预算 TotalCarat float64 json:总匹配克拉 DetailList []GemAllocateItem json:选用裸石明细 } // ToMap 转map用于打印输出和Python to_dict完全一致 func (dto *GemAllocateResultDTO) ToMap() map[string]interface{} { detail : make([]map[string]interface{}, 0, len(dto.DetailList)) for _, item : range dto.DetailList { detail append(detail, map[string]interface{}{ 宝石名称: item.StoneName, 取用克拉: common.RoundCarat(item.UseCarat), 花费金额: common.RoundMoney(item.UseCost), }) } return map[string]interface{}{ 预算总额: common.RoundMoney(dto.BudgetTotal), 实际花费: common.RoundMoney(dto.CostActual), 剩余预算: common.RoundMoney(dto.BudgetRemain), 总匹配克拉: common.RoundCarat(dto.TotalCarat), 选用裸石明细: detail, } } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:17 # User : geovindu # Product : GoLand # Project : goalgorithms # File : base_repo.go */ package repository import goalgorithms/greedy/entity // BaseGemRepository 仓储抽象接口可替换内存/Mysql/Redis type BaseGemRepository interface { AddGem(gem entity.GemStone) GetAllGems() []entity.GemStone ClearAll() Count() int } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:17 # User : geovindu # Product : GoLand # Project : goalgorithms # File : memory_repo.go */ package repository import goalgorithms/greedy/entity type GemMemoryRepository struct { storage []entity.GemStone } func NewGemMemoryRepository() *GemMemoryRepository { return GemMemoryRepository{ storage: make([]entity.GemStone, 0), } } func (r *GemMemoryRepository) AddGem(gem entity.GemStone) { r.storage append(r.storage, gem) } func (r *GemMemoryRepository) GetAllGems() []entity.GemStone { copyList : make([]entity.GemStone, len(r.storage)) copy(copyList, r.storage) return copyList } func (r *GemMemoryRepository) ClearAll() { r.storage r.storage[:0] } func (r *GemMemoryRepository) Count() int { return len(r.storage) } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:18 # User : geovindu # Product : GoLand # Project : goalgorithms # File : sort_strategy.go */ package algorithm import goalgorithms/greedy/entity // BaseSortStrategy 排序策略抽象策略模式可扩展 type BaseSortStrategy interface { Sort(gemList []entity.GemStone) []entity.GemStone } // UnitValueDescStrategy 性价比从高到低默认 type UnitValueDescStrategy struct{} func NewUnitValueDescStrategy() *UnitValueDescStrategy { return UnitValueDescStrategy{} } func (s *UnitValueDescStrategy) Sort(gemList []entity.GemStone) []entity.GemStone { list : make([]entity.GemStone, len(gemList)) copy(list, gemList) for i : 0; i len(list); i { for j : i 1; j len(list); j { if list[i].UnitCaratValue() list[j].UnitCaratValue() { list[i], list[j] list[j], list[i] } } } return list } // MaxCaratDescStrategy 扩展策略优先大克拉 type MaxCaratDescStrategy struct{} func NewMaxCaratDescStrategy() *MaxCaratDescStrategy { return MaxCaratDescStrategy{} } func (s *MaxCaratDescStrategy) Sort(gemList []entity.GemStone) []entity.GemStone { list : make([]entity.GemStone, len(gemList)) copy(list, gemList) for i : 0; i len(list); i { for j : i 1; j len(list); j { if list[i].TotalCarat list[j].TotalCarat { list[i], list[j] list[j], list[i] } } } return list } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:19 # User : geovindu # Product : GoLand # Project : goalgorithms # File : fraction_greedy.go */ package algorithm import ( goalgorithms/greedy/common goalgorithms/greedy/entity ) type GemFractionGreedy struct { sortStrategy BaseSortStrategy } // NewGemFractionGreedy 构造默认性价比排序策略 func NewGemFractionGreedy(strategy ...BaseSortStrategy) *GemFractionGreedy { alg : GemFractionGreedy{} if len(strategy) 0 { alg.sortStrategy strategy[0] } else { alg.sortStrategy NewUnitValueDescStrategy() } return alg } func (g *GemFractionGreedy) Calculate(gemList []entity.GemStone, budget float64) ([]entity.GemAllocateItem, error) { if budget common.EPS { return nil, common.NewBudgetZeroError() } sorted : g.sortStrategy.Sort(gemList) remainBudget : budget var result []entity.GemAllocateItem for _, gem : range sorted { if remainBudget common.EPS { break } var useCarat, useCost float64 if gem.BatchPrice remainBudget { useCarat gem.TotalCarat useCost gem.BatchPrice } else { ratio : remainBudget / gem.BatchPrice useCarat gem.TotalCarat * ratio useCost remainBudget } result append(result, entity.GemAllocateItem{ StoneName: gem.StoneName, UseCarat: useCarat, UseCost: useCost, }) remainBudget - useCost } return result, nil } /* * creater: geovindu * since: 2026-07-20 22:19:46 * LastAuthor: geovindu * lastTime: 2026-07-20 22:35:59 * 文件相对于项目的路径: \goalgorithms\greedy\service\gem_alloc_service.go * message: geovindu * IDE: vscode * Development: node.js 20, vuejs3.0 * package: * ISO: windows10 * database: mysql 8.0 sql server 2019 postgresSQL 16 * Copyright (c) 2026 by geovindu email:geovindu163.com, All Rights Reserved. */ /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:19 # User : geovindu # Product : GoLand # Project : goalgorithms # File : gem_alloc_service.go */ package service import ( goalgorithms/greedy/algorithm goalgorithms/greedy/common goalgorithms/greedy/entity goalgorithms/greedy/repository ) type GemAllocateService struct { repo repository.BaseGemRepository alg *algorithm.GemFractionGreedy } // NewGemAllocateService 依赖注入仓储算法 func NewGemAllocateService(repo repository.BaseGemRepository, alg *algorithm.GemFractionGreedy) *GemAllocateService { return GemAllocateService{ repo: repo, alg: alg, } } // AddStoneStock 业务层新增库存统一参数校验 func (s *GemAllocateService) AddStoneStock(stoneName string, totalCarat, batchPrice float64) error { if totalCarat common.EPS || batchPrice common.EPS { return common.NewGemParamInvalidError(克拉、价格必须大于0) } gem : entity.GemStone{ StoneName: stoneName, TotalCarat: totalCarat, BatchPrice: batchPrice, } s.repo.AddGem(gem) return nil } // Allocate 完整配石业务流程入口 func (s *GemAllocateService) Allocate(budget float64) (*entity.GemAllocateResultDTO, error) { gemList : s.repo.GetAllGems() if len(gemList) 0 { return nil, common.NewStockEmptyError() } items, err : s.alg.Calculate(gemList, budget) if err ! nil { return nil, err } var totalCarat, totalCost float64 for _, item : range items { totalCarat item.UseCarat totalCost item.UseCost } remain : budget - totalCost dto : entity.GemAllocateResultDTO{ BudgetTotal: budget, CostActual: totalCost, BudgetRemain: remain, TotalCarat: totalCarat, DetailList: items, } return dto, nil } // ClearStock 清空库存复用实例 func (s *GemAllocateService) ClearStock() { s.repo.ClearAll() } /* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:18 # User : geovindu # Product : GoLand # Project : goalgorithms # File : base_greedy.go */ package repository import goalgorithms/greedy/entity // BaseGemGreedy 贪心算法顶层抽象可替换实现 type BaseGemGreedy interface { Calculate(gemList []entity.GemStone, budget float64) ([]entity.GemAllocateItem, error) }调用/* # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看言語成了邀功盡責的功臣還需要行爲每日來值班嗎 # 描述Greedy Algorithm 贪心算法 # Author : geovindu,Geovin Du 涂聚文. # IDE : goLang 2024.3.6 go 26.2 # os : windows 10 # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j # Datetime : 2026/7/20 22:26 # User : geovindu # Product : GoLand # Project : goalgorithms # File : greedybll.go */ package bll import ( encoding/json fmt goalgorithms/greedy/algorithm goalgorithms/greedy/repository goalgorithms/greedy/service ) func demoCase1() { fmt.Println( 案例1性价比优先配石结果 ) repo : repository.NewGemMemoryRepository() alg : algorithm.NewGemFractionGreedy() // svc : service.NewGemAllocateService(repo, alg) // 录入库存 _ svc.AddStoneStock(0.8ct白钻, 0.8, 10500) _ svc.AddStoneStock(0.5ct白钻, 0.5, 6800) _ svc.AddStoneStock(0.3ct白钻, 0.3, 4200) _ svc.AddStoneStock(0.2ct粉钻, 0.2, 2800) dto, err : svc.Allocate(18000) if err ! nil { fmt.Println(错误, err) return } out, _ : json.MarshalIndent(dto.ToMap(), , ) fmt.Println(string(out)) } func demoCase2() { fmt.Println(\n 案例2优先大克拉配石结果 ) repo : repository.NewGemMemoryRepository() // 注入大克拉排序策略 strategy : algorithm.NewMaxCaratDescStrategy() alg : algorithm.NewGemFractionGreedy(strategy) svc : service.NewGemAllocateService(repo, alg) _ svc.AddStoneStock(0.8ct白钻, 0.8, 10500) _ svc.AddStoneStock(0.5ct白钻, 0.5, 6800) dto, err : svc.Allocate(12000) if err ! nil { fmt.Println(错误, err) return } out, _ : json.MarshalIndent(dto.ToMap(), , ) fmt.Println(string(out)) } func GreedyMain() { demoCase1() demoCase2() }输出绍了一个基于贪心算法的珠宝配石系统实现。系统采用Go语言开发包含以下核心组件基础模块定义常量、错误处理和数值计算工具实体层宝石库存、配石结果的数据结构仓储层内存存储实现支持CRUD操作算法层提供两种排序策略性价比优先/大克拉优先服务层完整的配石业务流程系统通过贪心算法实现珠宝配石优化可根据预算自动选择最佳宝石组合。演示案例展示了不同策略下的配石结果输出包含预算使用情况、匹配克拉数和详细配石清单。代码结构清晰采用分层设计和策略模式便于扩展和维护。