Adjacent number algorithm grouper

前端 未结 13 1744
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  抹茶落季
    2021-02-15 07:29

    Erlang , perform also sort and unique on input and can generate programmatically reusable pair and also a string representation.

    group(List) ->
        [First|_] = USList = lists:usort(List),
        getnext(USList, First, 0).
    getnext([Head|Tail] = List, First, N) when First+N == Head ->
        getnext(Tail, First, N+1);
    getnext([Head|Tail] = List, First, N) ->
        [ {First, First+N-1} | getnext(List, Head, 0) ];
    getnext([], First, N) -> [{First, First+N-1}].
    %%%%%% pretty printer
    group_to_string({X,X}) -> integer_to_list(X);
    group_to_string({X,Y}) -> integer_to_list(X) ++ "-" ++ integer_to_list(Y);
    group_to_string(List) -> [group_to_string(X) || X <- group(List)].
    

    Test getting programmatically reusable pairs:

    shell> testing:group([34,3415,56,58,57,11,12,13,1,2,3,3,4,5]).

    result> [{1,5},{11,13},{34,34},{56,58},{3415,3415}]

    Test getting "pretty" string:

    shell> testing:group_to_string([34,3415,56,58,57,11,12,13,1,2,3,3,4,5]).

    result> ["1-5","11-13","34","56-58","3415"]

    hope it helps bye

提交回复
热议问题