问题描述
我们有一组介于 [1,..,4]
之间的整数值。我们希望将特定值分配到 [1,...,10]
之间的不同长度的段中,以 1 为基础。
我们在下表中展示了一个示例:
Example Value segments distribution
a 4 4 1 on each segment
b 3 4 1 on the first 3 segments
c 3 2 2 on the first segment ( 1 + 1) and 1 on the second segment
我的解决方案如下:
- if value >= segments 然后遍历该段并为每个段加 1 直到 dispatch 等于 value
- if value < segments 然后以递减顺序在段上循环并为每个段加 1 直到我们到达第一个段。求值与1的总和的差,然后将其添加到第一段
源代码
所有示例(a、b、c)都用以下代码表示。输出如下:
#example a [1, 1, 1, 1]
#example b [1, 1, 1, 0]
#example c [2, 1]
#!/usr/bin/env python
import os
import re
import sys
import argparse
if __name__ == "__main__":
threshold = 4
#(a) value = 3 and segments = 4
dispatch = 1
value = 4 + 1
seg1 = [0,0,0,0]
for i in range(0, len(seg1)):
if dispatch == value:
break
seg1[i] += 1
dispatch += 1
print ("example a %s" %seg1)
# (b) value = 3 and segments = 4
dispatch = 1
value = 3 + 1
seg2 = [0,0,0,0]
for i in range(0, len(seg2)):
if dispatch == value:
break
seg2[i] += 1
dispatch += 1
print ("example b %s" %seg2)
# (c) value = 3 and segments = 2
value = 3 + 1
dispatch = 1
seg3 = [0,0]
for i in range(len(seg3) - 1, -1, -1):
if i == 0:
seg3[i] = value - dispatch
break
seg3[i] += 1
dispatch += 1
print ("example c %s" %seg3)
问题
我发现我使用的解决方案非常丑陋。我无法从示例中推断出公式。是否有我们可以从示例中推导出的公式?这将使算法背后有一个公式,哈哈
My code is in C but i found it easier to represent it in python in here.
最佳答案
数学公式很简单:
value / segments
至少给出了每个段中必须放置的项目数
value % segments
为您提供接收额外项目的段数
用你的例子:
v/s v%s
a 4 4 1 0
b 3 4 0 3
c 3 2 1 1
这样,您就得到了一个非常简单的算法:
unsigned int n = value/segments;
unsigned int c = value%segments;
for(unsigned int i = 0; i < segments; ++i)
theSegments[i] = n + (i < c);
或者,如果你想跳过数组:
unsigned int f(unsigned int values, unsigned int segments, theSegment)
{
// assuming theSegment being checked for < segments
return value/segments + (theSegment < value%segments)
}
如果您想使用从 1 开始的数组(索引 0 作为虚拟数组):
for(unsigned int i = 1; i <= segments; ++i)
theSegments[i] = n + (i <= c);
关于python - 如何基于 1 在一组段上分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460508/