Skip to content

Instantly share code, notes, and snippets.

@betawaffle
Created September 29, 2012 00:20
Show Gist options
  • Save betawaffle/3802716 to your computer and use it in GitHub Desktop.
Save betawaffle/3802716 to your computer and use it in GitHub Desktop.
Bash Expansion Interview Answer
expand(Bin) ->
expand_1(Bin, [<<>>], []).
append(C, Prefixes) ->
lists:map(fun (Prefix) ->
<<Prefix/binary, C>>
end, Prefixes).
expand_1(Bin, Prefixes, Acc) ->
expand_1(Bin, Prefixes, Prefixes, Acc).
expand_1(<<C, Rest/binary>>, Pre0, Cur0, Acc0) ->
case expand_2(C, Pre0, Cur0, Acc0) of
{Pre1, Acc1} ->
expand_1(Rest, Pre1, Acc1);
{Pre1, Cur1, Acc1} ->
expand_1(Rest, Pre1, Cur1, Acc1)
end;
expand_1(<<>>, _, Cur, Acc) ->
lists:reverse(Cur, Acc).
expand_2(C, Pre, Cur, Acc) ->
case C of
$} -> {Cur ++ Acc, []};
${ -> {Cur, Cur, Acc};
$, -> {Pre, Pre, Cur ++ Acc};
_ -> {Pre, append(C, Cur), Acc}
end.
def expand str
_, res, _ = str.each_char.reduce([[''], [''], []]) do |(pre, cur, acc), c|
case c
when '}'; [acc + cur, acc + cur, []]
when '{'; [cur, cur, acc]
when ','; [pre, pre, acc + cur]
else ; [pre, cur.map { |x| x + c }, acc]
end
end
res
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment