假设我有两个字符串只有一个字符:
'aaaaaaa'
'bbb'
我想找一个算法来产生一个组合字符串:
'aabaabaaba'
这两个被合并,因此来自任一列表的连续字符数最少(在这种情况下,#是2)。每个字符串的长度是任意的,我希望它是对称的。奖励点用于将其扩展到超过2个字符串。
我在python中这样做,但语言并不重要。这是我正在处理的负载平衡问题。
答案 0 :(得分:2)
您可以选择使用这些元素,并在必要时使用较长字符串的字母。您可以确定整数算术是否可以使用附加字母:分数告诉您每个字母对之间有多少个字母。只要累积分数大于½:
,就会积累此分数并使用较长数组中的字母def intertwine(a, b):
""" Return a combination of string with fewest number of
consecutive elements from one string
"""
if len(b) > len(a):
return intertwine(b, a)
if not b:
return a
a = list(a)
b = list(b)
num = len(a) - len(b)
denom = len(b)
acc = 0
res = []
while a or b:
acc += num
while acc >= denom / 2:
if a: res += a.pop(0)
acc -= num
if a: res += a.pop(0)
if b: res += b.pop(0)
return "".join(res)
print intertwine("aaabaaa", "bbb") # "aababbaaba"
print intertwine("aaaaaaa", "b") # "aaabaaaa"
print intertwine("aaaaaa", "b") # "aaabaaa"
print intertwine("aa", "bbbbbb") # "bbabbabb"
print intertwine("", "bbbbbb") # "bbbbbb"
print intertwine("", "") # ""
答案 1 :(得分:0)
import itertools
def intermix(*containers):
mix = []
for c in sorted(containers, key=lambda c: len(c)):
if len(c) >= len(mix):
bigger, smaller = c, mix
else:
bigger, smaller = mix, c
ratio, remainder = divmod(len(bigger), len(smaller) + 1)
chunk_sizes = (ratio + (1 if i < remainder else 0) for i in range(len(smaller) + 1))
chunk_offsets = itertools.accumulate(chunk_sizes)
off_start = 0
new_mix = []
for i, off in enumerate(chunk_offsets):
new_mix.extend(bigger[off_start:off])
if i == len(smaller):
break
new_mix.append(smaller[i])
off_start = off
mix = new_mix
return mix