Skip to content

Instantly share code, notes, and snippets.

@dnery
Last active March 25, 2019 12:54
Show Gist options
  • Save dnery/d4feadba61e01882b53943a9f0a78550 to your computer and use it in GitHub Desktop.
Save dnery/d4feadba61e01882b53943a9f0a78550 to your computer and use it in GitHub Desktop.
dailyprogrammer #279 solution attempt in erlang
- module(solution).
- export([prettify/1,reflow/1,justify/1]).
% module entry point
%
prettify(A) -> lists:concat
(justify(reflow(re:split(A, "\\s+", [{return, list}])))).
% reflow calculator function
%
reflow([]) -> [];
reflow([H|[]]) -> [H ++ "~n"];
reflow([H1,H2|T]) when (length(H1) + length(H2) + 1 =< 40) ->
reflow([H1 ++ " " ++ H2|T]);
reflow([H1,H2|T]) -> [H1 ++ "~n"] ++ reflow([H2|T]).
% justify string sizes to close 40
%
justify([]) -> [];
justify([H|[]]) -> [H];
justify([H|T]) ->
case (length(H) + string:words(H) - 1 =< 40) of
true -> justify([re:replace(H, " ", " ", [global, {return, list}])|T]);
false -> [H] ++ justify(T)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment