Skip to content

Instantly share code, notes, and snippets.

@henrik
Created August 18, 2022 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrik/b81bd702fe7c183c49b2a42199d216f4 to your computer and use it in GitHub Desktop.
Save henrik/b81bd702fe7c183c49b2a42199d216f4 to your computer and use it in GitHub Desktop.
Similar to `Enumerable#chunk_while`, where it tries to make each chunk sum to no more than `max`.
# Similar to `Enumerable#chunk_while`, where it tries to make each chunk sum to no more than `max`.
# If a value is greater than `max`, it becomes its own chunk. (This is the "desired" part – we don't reject values higher than `max`.)
class ChunkByDesiredMaxValue
def self.call(enum, max, &block)
block ||= -> { _1 }
sum = 0
enum.chunk_while { |a, b|
a_value = block.(a)
b_value = block.(b)
sum += a_value
if sum + b_value > max
sum = 0
false # Split between a and b.
else
true # Keep a and b together.
end
}
end
end
# Silly example:
input = [ 7, 2, 3, 7, 11, 1, 2, 1, 3, 5, 9, 12, 5, 5, 5, 5 ].map(&:to_s)
pp ChunkByDesiredMaxValue.call(input, 10) { _1.to_i }.to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment