我有两个不同长度的数组。我想将它们放入哈希中,尽可能均匀地分布元素。
编辑:对不起,我意识到我没有提供足够的输入。“尽可能均匀”是指以下内容:
array1 总是比 array2 有更多的元素。
array2 元素是字符串。最小的单位是单词。
更新的目标 对于生成的哈希,我希望根据平均字数比(所有元素 array2 到 array1.join(" ").split(" "))将值分配给键。这样我就可以在不破坏字符串完整性的情况下将数字分配到尽可能接近平均值的字符串。您还可以将结果显示为:
result = {"The older son of a woman" =>[320, 321, 322, 323],...}
我很抱歉造成混乱,我想应用程序的目的让我以某种颠倒的方式想到了这一点..
我可以让下面的示例代码在某些情况下工作,但在某些情况下却不行。
array1.clear
array2.clear
array11 = [336, 337, 338, 339, 340, 342, 344, 345, 346, 347, 348]
array22 = ["New research", "suggests that hoarders have unique patterns", "of brain activity", "when faced with making decisions", "about their possessions."]
array1 = [320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 331, 332, 333, 334]
array2 = ["The older son of a woman", "killed at Sunday's mass shooting", "in Wisconsin said she was shot just", "after completing prayers."]
def hash_from_arrays(array1, array2)
hash = Hash.new{|h,k| h[k] = [] }
arr_ratio = arr1_to_arr2_ratio(array2, array1)
start = 0
last_arr1_to_arr2 = Float(Float(array2.last.split(" ").length)*Float(arr_ratio)).floor
array1.each_with_index do | element, index|
arr1_for_arr2_ratio = Float(Float(array2[0].split(" ").length)*Float(arr_ratio)).floor
hash[element] = array2[0]
if arr1_for_arr2_ratio + start == index && array2.length > 1
array2.shift
start = index
end
end
return hash
end
def arr1_to_arr2_ratio(array1, array2)
word_count = 0.0
array1.each{|string| word_count = word_count + string.split(" ").length}
result = Float(array2.length) / word_count
return result
end
hash_from_arrays(array1, array2)
=> {320=>"The older son of a woman", 321=>"The older son of a woman", 322=>"The older son of a woman", 323=>"The older son of a woman", 324=>"The older son of a woman", 325=>"killed at Sunday's mass shooting", 326=>"killed at Sunday's mass shooting", 327=>"killed at Sunday's mass shooting", 328=>"in Wisconsin said she was shot just", 329=>"in Wisconsin said she was shot just", 331=>"in Wisconsin said she was shot just", 332=>"in Wisconsin said she was shot just", 333=>"after completing prayers.", 334=>"after completing prayers."}
编辑更新了代码,现在它适用于两个数组。我想一般都有效...如果有人可以提出更好的解决方案,那就太好了。