Guest User

Untitled

a guest
Jan 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. -module(np).
  2. -export([main/0]).
  3.  
  4. -define(LIST_LENGTH, 100).
  5.  
  6. main() ->
  7. Source = create_test_list(?LIST_LENGTH),
  8. product_all_lists(Source, 0).
  9.  
  10. product_all_lists([], Count) ->
  11. receive_product_lists_result([], 0, Count);
  12. product_all_lists([L1], Count) ->
  13. receive_product_lists_result([L1], 0, Count);
  14. product_all_lists([L1, L2 | T], Count) ->
  15. Pid = self(),
  16. spawn_link(fun() ->
  17. product_lists(Pid, [L1, L2])
  18. end),
  19. product_all_lists(T, Count + 1).
  20.  
  21. receive_product_lists_result([L1], Count, Limit) when Count == Limit ->
  22. io:format("Result: ~p~n", [L1]);
  23. receive_product_lists_result(Result, Count, Limit) when Count == Limit ->
  24. product_all_lists(Result, 0);
  25. receive_product_lists_result(Result, Count, Limit) ->
  26. receive
  27. List ->
  28. receive_product_lists_result([List | Result], Count + 1, Limit)
  29. end.
  30.  
  31.  
  32. product_lists(ParentPid, [L1, L2]) ->
  33. Result = product_lists(L1, L2, []),
  34. ParentPid ! Result.
  35.  
  36. product_lists([], _, Result) ->
  37. Result;
  38. product_lists([H | T], L2, Result) ->
  39. case lists:member(H, L2) of
  40. true ->
  41. product_lists(T, L2, [H | Result]);
  42. false ->
  43. product_lists(T, L2, Result)
  44. end.
  45.  
  46. %% Creating test data.
  47.  
  48. create_test_list(Length) ->
  49. Seq = lists:seq(1, Length),
  50. create_test_list(Seq, [], Length, 0).
  51.  
  52. create_test_list(_, Result, Length, Count) when Length == Count ->
  53. Result;
  54. create_test_list(Seq, Result, Length, Count) ->
  55. Sorted = create_rand_list(Seq),
  56. create_test_list(Seq, [Sorted | Result], Length, Count + 1).
  57.  
  58. create_rand_list(Source) ->
  59. create_rand_list(Source, []).
  60.  
  61. create_rand_list([], Result) ->
  62. Length = crypto:rand_uniform(?LIST_LENGTH - 5, ?LIST_LENGTH),
  63. lists:sublist(Result, Length);
  64. create_rand_list(Source, Result) ->
  65. Length = length(Source),
  66. Position = crypto:rand_uniform(0, Length),
  67. Value = get_value_at(Source, Position),
  68. create_rand_list(lists:delete(Value, Source), [Value | Result]).
  69.  
  70. get_value_at(Source, Position) ->
  71. get_value_at(Source, Position, 0).
  72.  
  73. get_value_at([], _, _) ->
  74. throw("Position too big.");
  75. get_value_at([H | _], Position, Count) when Position == Count ->
  76. H;
  77. get_value_at([_ | T], Position, Count) ->
  78. get_value_at(T, Position, Count + 1).
Add Comment
Please, Sign In to add comment