ruby - How to decompose an integer into a array of integers -
lets have number of "things", instance 7
.
but can store "things" in groups of maximum "2" units. need this:
7 ----> [2, 2, 2, 1]
the obvious method if make loop through it
def decompose(qty, group_max) ret = [] while qty > 0 if qty < group_max ret.push qty qty = 0 else ret.push group_max qty -= group_max end end ret end decompose 7, 2
while works... not ellegant. wondering if maybe there method in integer or array structure can use improve code.
i find cleaner things like
myarray.map {|x| ... }
and wondering if there similar might me this.
you can as:
qty = 15 # group_size = 2 count_of_groups = qty / group_size result = [group_size] * count_of_groups remaining = qty % group_size result += [remaining] if remaining != 0 result # [2, 2, 2, 2, 2, 2, 2, 1]
Comments
Post a Comment