Skip to content

Instantly share code, notes, and snippets.

@yamasushi
Last active June 22, 2019 10:54
Show Gist options
  • Select an option

  • Save yamasushi/69d6f5ab6cd7115ab525fe011ec67dfe to your computer and use it in GitHub Desktop.

Select an option

Save yamasushi/69d6f5ab6cd7115ab525fe011ec67dfe to your computer and use it in GitHub Desktop.
%% Erlang Programming Exercise 3-10
%% https://gist.github.com/yamasushi/69d6f5ab6cd7115ab525fe011ec67dfe
-module(ex310).
-export([test_data/0,fill/2,justify/2]).
fill(Words,Width) ->
GW = gather_words_acc(Words,Width,0,0,[],[]),
%% io:format("~p~n",[GW]),
lists:foreach(fun(K)->io:format("~s~n",[K]) end ,
lists:map(fun({_,L}) -> fill_line(L) end, GW)).
justify(Words,Width) ->
GW = gather_words_acc(Words,Width,0,0,[],[]),
%% io:format("~p~n",[GW]),
lists:foreach(fun(K)->io:format("~s~n",[K]) end ,
lists:map(fun({LW,L}) -> justify_line(L,LW,Width) end, GW)).
gather_words_acc([], _Width, LenWords, _LenLine, AccLine, Acc) ->
lists:reverse([{LenWords, lists:reverse(AccLine) } |Acc]);
gather_words_acc([H|T], Width, LenWords, LenLine, AccLine, Acc) ->
LenWord=length(H),
if
(LenWord+LenLine+1) > Width ->
gather_words_acc(T, Width, LenWord, LenWord,
[H], [{LenWords, lists:reverse(AccLine)} |Acc]);
true ->
gather_words_acc(T, Width , LenWords+LenWord, LenLine+LenWord+1,
[H|AccLine],Acc)
end.
fill_line([H]) -> H;
fill_line([H|T]) -> H ++ " " ++ fill_line(T).
justify_line([H], _LenWords, _Width) -> H;
justify_line(L, LenWords, Width) ->
N = length(L),
Spc = Width-LenWords,
SpcUnit = Spc div (N-1),
justify_concat_acc(L, Spc, SpcUnit, []).
justify_concat_acc([H1,H2], Spc, _SpcUnit, Acc) ->
%% io:format(">>>>> ~p,~p | ~p (~w)~n~n", [H1, H2, Acc, Spc]),
lists:concat(lists:reverse([H2, lists:duplicate(Spc, $\s), H1 | Acc]));
justify_concat_acc([H|T], Spc, SpcUnit, Acc) ->
io:format("~p,~p,~p,~p~n",[[H|T],Acc,Spc,SpcUnit]),
justify_concat_acc(T, Spc-SpcUnit, SpcUnit,
[lists:duplicate(SpcUnit,$\s),H|Acc]).
test_data() ->
{ok,S} = file:read_file("test.dat"),
string:lexemes(binary_to_list(S)," \n") .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment