这是一个基于哈希表的快速草稿。首先,计算需要多少组。将输入的大小除以组大小并向上取整。然后创建用于存储元素的集合。遍历输入并将每个元素存储到一个集合中。
缺少的是如何处理重复项。查找是否存在很容易,因为哈希表有 .ContainsKey() 方法就是为了这个。如何获取另一个哈希表的逻辑留给读者作为练习。
此解决方案不保留原始顺序,因为哈希表根据定义是无序集。还有ordered dictionary,可以通过类型加速器[ordered]访问。
# Some test cases
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary') # 11 unique elements
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary', 'laurel') # 12 unique elements
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'parsely', 'chives', 'sage', 'fennel', 'oregano', 'thyme', 'tarragon', 'rosemary') # 12 elements, one duplicate, good index
$data = @('basil', 'marjoram', 'aniseed', 'parsely', 'chives', 'sage', 'fennel', 'parsely', 'oregano', 'thyme', 'tarragon', 'rosemary') # 12 elements, one duplicate, bad index
# How big a group will be
$groupMaxSize = 4
# Divide list size with group size and round up
# This many groups are needed
$numGroups = [math]::ceiling($data.Count / $groupMaxSize)
# Create hash table for each group. Store in an array
$hh = @()
for($i=0;$i -le $numGroups; ++$i) {
$hh += @{}
}
# Iterate through the data. Each element index mod numGroups will tell
# into which group it will belong.
for($i=0;$i -lt $data.Count; ++$i) {
# Which group will the element go into?
$idx = $i % $numGroups
# Hashtable requires unique keys, so only add elements that don't exist.
# Key is the data, value is group index.
if(-not $hh[$idx].ContainsKey($data[$i])) {
$hh[$idx].Add($data[$i], $idx)
} else {
# Element alreayd existed, add logic to look up next free hashtable
write-host "collision!" $data[$i]
}
}
# print results
$hh
collision! parsely
Name Value
---- -----
basil 0
chives 0
oregano 0
thyme 1
marjoram 1
sage 1
aniseed 2
fennel 2
tarragon 2
rosemary 3
parsely 3