How to split a list of strings into given number of lists in erlang -
given list , integer, want split list specified number of lists (inside list).
for example:
input:
[1,2,3,4,5,6,7,8,9], 3
output:
[[1,2,3],[4,5,6],[7,8,9]]
what clean , efficient way this?
the solution written steve vinoski calls length/1
in guard each partition makes o(n^2)
. bothers me because can done in o(n)
, performance freak. can done in many ways example there one:
divide(l, n) when is_integer(n), n > 0 -> divide(n, 0, l, []). divide(_, _, [], acc) -> [lists:reverse(acc)]; divide(n, n, l, acc) -> [lists:reverse(acc) | divide(n, 0, l, [])]; divide(n, x, [h|t], acc) -> divide(n, x+1, t, [h|acc]).
or modification of steve's solution
divide(l, n) -> divide(l, n, []). divide([], _, acc) -> lists:reverse(acc); divide(l, n, acc) -> try lists:split(n, l) of {h,t} -> divide(t, n, [h|acc]) catch error:badarg -> lists:reverse([l|acc]) end.
or simpler:
divide([], _) -> []; divide(l, n) -> try lists:split(n, l) of {h,t} -> [h|divide(t, n)] catch error:badarg -> [l] end.
Comments
Post a Comment