Erlang分布式反向字符串

时间:2019-04-30 07:53:07

标签: erlang

我是erlang的新手,我不知道如何解决此练习。
我需要通过将长字符串划分为N个子字符串来反转长字符串,反转单个子字符串,然后将它们加入以获得原始字符串的反转。 每个子字符串都需要通过不同的过程反转。

我的问题是:
1)如何将字符串分成N个大小相等的子字符串?
2)如何连接其他进程收到的字符串?

有人可以给我示例代码吗?这是我所做的,但是缺少主要部分:

% This function should split the string, spawn the processes
% and recombine the results
reverse(Str, N) -> % ...

sub_reverse() ->
    receive
        { From, SubStr } -> From ! { self(), lists:reverse(SubStr) }
    end.

2 个答案:

答案 0 :(得分:4)

尝试这样的事情。

-module(stackoverflow).
-export([reverse/2, join/0, sub_reverse/2]).

reverse(Str, N) ->
    % A process joining the reversed substrings.
    JoinPID = spawn(stackoverflow, join, []),

    % The step size is the length of Str divided by N.
    % TODO Handle remainder.
    Step = string:length(Str) div N,

    % The split points are calculated from end to start of Str.
    SplitPoints = lists:seq(string:length(Str) - Step, 0, -Step),

    % For each split point, spwan a process that reverts the substring for the
    % split point.
    lists:foreach(fun(From) ->
                    Substr = string:slice(Str, From, Step),
                    spawn(stackoverflow, sub_reverse, [JoinPID, Substr])
                  end,
                  SplitPoints).

join() ->
    receive
        {reverse_str, ReverseStr} ->
            io:format("~s", [ReverseStr]),
            join()
    end.

sub_reverse(JoinPID, SubStr) ->
    JoinPID ! {reverse_str, lists:reverse(SubStr)}.

修改

此方法有效,但取决于Spawend流程的顺序。如果它们返回故障,则join()接收到故障零件。因此,可能的改进可能是为每个部分加上From标记,以便join()可以按正确的顺序加入它们。这留给读者练习。

答案 1 :(得分:1)

答案之后是我的版本:

-module(reverse).
-export([reverse/1, join/3, sub_reverse/3]).

reverse("") -> "";
reverse(Str) ->
    Step = ceil(string:length(Str) / 10),
    SplitPoints = lists:seq(0, string:length(Str) - 1, Step),

    JoinPid = spawn(reverse, join, [self(), [], length(SplitPoints)]),

    lists:foreach(
        fun (Start) ->
            IndexPos = Start div Step,
            SubStr = string:slice(Str, Start, Step),
            spawn(reverse, sub_reverse, [JoinPid, IndexPos, SubStr])
        end,
    SplitPoints),

    receive
        { joined, ReversedStr } -> io:format("~p", [ReversedStr])
    end.

join(ReversePid, Acc, N) ->
    case length(Acc) of
        N ->
            Parts = lists:sort(fun ({A, _}, {B, _}) -> A > B end, Acc),
            Str = string:join(lists:map(fun ({_, SubStr}) -> SubStr end, Parts), ""),
            ReversePid ! { joined, Str };
        _ ->
            receive
                {reversed, X} -> join(ReversePid, [X | Acc], N)
            end
    end.


sub_reverse(JoinPid, IndexPos, SubStr) ->
    JoinPid ! {reversed, { IndexPos, string:reverse(SubStr) } }.