Skip to content

Instantly share code, notes, and snippets.

@acamino
Created December 24, 2019 18:48
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 acamino/da87b09a5ccb787b2c44a93a8ff06f12 to your computer and use it in GitHub Desktop.
Save acamino/da87b09a5ccb787b2c44a93a8ff06f12 to your computer and use it in GitHub Desktop.
Section an array by the given lengths
# section :: [a] -> [Int] -> [[a]]
section = lambda { |arr:, lengths:|
starts = [*0..lengths.size - 1].reduce([]) do |acc, idx|
acc << lengths.take(idx).sum; acc
end
starts.zip(lengths).map { |start, lenght| arr.slice(start, lenght) }
}
arr = [*1..100]
lengths = [28, 31, 32, 9]
p section.call(arr: arr, lengths: lengths).map(&:length) == lengths
p section.call(arr: arr, lengths: lengths)
# [
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], # 12
# [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], # 11
# [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45], # 22
# [46, 47, 48, 49, 50] # 5
# ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment