一组字符的均匀分布 [英] uniform distribution of a set of characters

查看:85
本文介绍了一组字符的均匀分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一组字符需要均匀分布在数组中。
例如,

There is a set of characters that needs to be uniformly distributed in an array. For example,

a-1

b -2

c-3

d-4

在这种情况下,有一个a,两个b,三个c和四个d,共有10个字符。

In this case there is one a, two b, three c and four d with a total of 10 characters.

现在,我需要将其分配为大小为10的数组,以便所有平均分配。他们不必完全均匀地分布,任何接近的事情都可以。

Now I need to distribute it in an array of size 10 so that all of them are evenly distributed. they don't have to be exactly uniformly distributed, anything close will do.

例如这是一个有效的序列。

For ex. this is a valid sequence.

dcdbcdadcb

d c d b c d a d c b

推荐答案

您可以使用类似于bresenham算法的方法,用于跟踪每个组件的理想间距和最后间距之间的误差:

You could use something similar to the bresenham algorithm to track the error between the ideal spacing and the last spacing for each component:

vals = ['a','b','c','d']
cts  = [1,2,3,4]

sz = sum(cts)
spacing = [float(sz)/(ct+1) for ct in cts]
err = [s for s in spacing]
a=[]
for i in range(sz):
    err = [e-1 for e in err]
    m = min(err)
    i = err.index(m)
    a.append(vals[i])
    err[i]+=spacing[i]
print a

产量: ['d','c','b','d','a','c','d','b','c','d']

这篇关于一组字符的均匀分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆