

' 按权重比例生成随机数Private Function GenerateNumbersByWeight(targetValue As Double, weights() As Double, isInteger As Boolean) As Double()Dim count As Integer = weights.LengthDim numbers(count - 1) As Double' 为每个权重添加少量随机波动(可选)For i As Integer = 0 To count - 1' 基础值按权重计算Dim baseValue As Double = targetValue * weights(i)' 添加 ±10% 的随机波动Dim fluctuation As Double = baseValue * 0.1 * (random.NextDouble() * 2 - 1)Dim randomValue As Double = baseValue + fluctuationIf isInteger Thennumbers(i) = Math.Round(randomValue)Elsenumbers(i) = Math.Round(randomValue, 2)End IfNext' 调整第一个数确保总和等于目标值Dim actualSum As Double = numbers.Sum()Dim adjustment As Double = targetValue - actualSumIf isInteger Thennumbers(0) = Math.Round(numbers(0) + adjustment)Elsenumbers(0) = Math.Round(numbers(0) + adjustment, 2)End IfReturn numbersEnd Function

' ================================================================' 模式一:几个和=原数' 使用"前瞻法":每次生成时预留后续数的空间,确保最后一个数合法' ================================================================Private Function GenerateBySum(targetValue As Double, splitCount As Integer,minVal As Double, maxVal As Double,isInteger As Boolean) As Double()Dim numbers(splitCount - 1) As DoubleDim sumSoFar As Double = 0Dim remainingCount As Integer = splitCountFor i As Integer = 0 To splitCount - 1remainingCount -= 1' 剩余数至少需要的最小总和Dim needMin As Double = remainingCount * minVal' 剩余数至多能接受的最大总和Dim needMax As Double = remainingCount * maxVal' 当前数可取范围Dim low As Double = Math.Max(minVal, targetValue - sumSoFar - needMax)Dim high As Double = Math.Min(maxVal, targetValue - sumSoFar - needMin)If low > high Then' 约束冲突,取中点逼近low = minValhigh = maxValEnd IfIf isInteger Thenlow = Math.Ceiling(low)high = Math.Floor(high)If low > high Then low = highnumbers(i) = Math.Round(low + random.NextDouble() * (high - low))Elsenumbers(i) = Math.Round(low + random.NextDouble() * (high - low), 2)End IfsumSoFar += numbers(i)NextReturn numbersEnd Function
夜雨聆风