Skip to content

Instantly share code, notes, and snippets.

@jcfigueiredo jcfigueiredo/kata 1
Last active Dec 23, 2015

Embed
What would you like to do?
-module(kata).
-export([justify/1, format/1]).
-define(MaxSize, 30).
justify([]) -> [];
justify([Phrase]) ->
justify(hd(Phrase), tl(Phrase), ?MaxSize);
justify(Phrase) ->
Justified = justify(string:tokens(Phrase, " ")),
lists:map(fun(X) -> kata:format(X) end, Justified).
justify(H, [], _) ->
[H];
justify(H, T, N) when N > ?MaxSize ->
[H] ++ justify(hd(T), tl(T), ?MaxSize);
justify(H, T, N) when N =< ?MaxSize ->
Ht = hd(T), Nh = H ++ " " ++ Ht,
Size = length(Nh) + length(Ht),
justify(Nh, tl(T), Size).
format(Phrase) when length(Phrase) < ?MaxSize ->
format(Phrase, " ");
format(Phrase) ->
Phrase.
format(Phrase, Separator) when length(Phrase) > ?MaxSize ->
NewSeparator = string:copies(" ", string:len(Separator) - 1),
NewPrase = re:replace(Phrase, Separator, NewSeparator, [{return,list}]),
format(NewPrase, Separator);
format(Phrase, Separator) when length(Phrase) < ?MaxSize ->
NewSeparator = string:copies(" ", string:len(Separator) + 1),
NewPrase = re:replace(Phrase, "\s+", NewSeparator, [global,{return,list}]),
format(NewPrase, NewSeparator);
format(Phrase, _) ->
Phrase.
% kata:justify("Sweet pepper ricebean salsify sierra leone bologi mung bean catsear cabbage. Kohlrabi desert raisin lettuce cucumber bok choy soko cress scallion groundnut tomatillo catsear.").
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.