Skip to content

Instantly share code, notes, and snippets.

@datapimp
Created February 26, 2012 23:38
Show Gist options
  • Select an option

  • Save datapimp/1919804 to your computer and use it in GitHub Desktop.

Select an option

Save datapimp/1919804 to your computer and use it in GitHub Desktop.
sample = {}
headers = 20.times.collect {|n| "Header #{n}"}
sample = headers.inject({}) do |memo,header|
memo[ header ] = (rand(8).to_i).times.collect {|j| " item #{ j }"}
memo
end
flattened = sample.flatten
threshold = sample.inject(0) do |weight,item|
weight += 2
weight += item[1].size if item.is_a?(Array)
weight
end
threshold = threshold / 3
current_weight = 0
current_index = 0
sorted = 3.times.collect {[]}
sample.each do |header,values|
next unless values.length > 0
if current_weight > threshold
current_index += 1
current_weight = 0
end
current_weight += 2 + values.size
sorted[current_index] << [header,values]
end
index = 0
weights = sorted.inject({}) do |memo,set|
memo[index] = sorted[index].inject(0) do |acc,item|
acc += 2 + item[0].size
end
index = index + 1
memo
end
puts weights.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment