erlang 黑客等级最大化XOR Erlang

黑客等级最大化XOR Erlang

maximize_xor.erl
-module(maximize_xor).
-export([main/0, test/0]).
-import(lists, [map/2, seq/2]).

main() ->
  I = {inputs, [2,4]},
  {inputs, [START|[STOP|_]]} = I,
  EXPANDED_GROUP = lists:seq(START,STOP),
  GROUPS = organize(EXPANDED_GROUP),
  MAX = maximize_bxor(GROUPS, 0),
  log(MAX).

organize(COUNTS) ->
  process(COUNTS, []).

log(MSG) -> io:format("~w~n",[MSG]).

%For HackerRank
inputs() ->
  {ok, [L, R]} = io:fread("", "~d~d"),
  {inputs, [L, R]}.

process([H|T], THUSFAR) ->
  THUSFAR1 = THUSFAR ++ lists:map(
    fun(X)-> {group,[H,X]} end, [H]++T
  ),
  process(T,THUSFAR1);
process([], THUSFAR) -> THUSFAR.

maximize_bxor([H|T], MAX) ->
  {group,[A,B]} = H,
  MAX1 = A bxor B,
  if
    MAX1 > MAX ->
        MAX2 = MAX1;
    true ->
        MAX2 = MAX
  end,
  maximize_bxor(T, MAX2);
maximize_bxor([], MAX) -> MAX.

test() ->
  [
    {group, {result, group_test()} },
    {maximize_2_4, {result, maximize_xor_test1()} },
    {maximize_1_10, {result, maximize_xor_test2()} }
  ].

group_test() ->
  Y = [2,3,4],
  [{group,[2,2]},{group,[2,3]},{group,[2,4]},{group,[3,3]},{group,[3,4]},{group,[4,4]}] = organize(Y),
  success.

maximize_xor_test1() ->
  GROUPS = [{group,[2,2]},{group,[2,3]},{group,[2,4]},{group,[3,3]},{group,[3,4]},{group,[4,4]}],
  7 = maximize_bxor(GROUPS, 0),
  success.

maximize_xor_test2() ->
  GROUPS = [
    {group,[1,1]},{group,[1,2]},{group,[1,3]},{group,[1,4]},{group,[1,5]},{group,[1,6]},{group,[1,7]},{group,[1,8]},{group,[1,9]},{group,[1,10]},
    {group,[2,2]},{group,[2,3]},{group,[2,4]},{group,[2,5]},{group,[2,6]},{group,[2,7]},{group,[2,8]},{group,[2,9]},{group,[2,10]},
    {group,[3,3]},{group,[3,4]},{group,[3,5]},{group,[3,6]},{group,[3,7]},{group,[3,8]},{group,[3,9]},{group,[3,10]},
    {group,[4,4]},{group,[4,5]},{group,[4,6]},{group,[4,7]},{group,[4,8]},{group,[4,9]},{group,[4,10]},
    {group,[5,5]},{group,[5,6]},{group,[5,7]},{group,[5,8]},{group,[5,9]},{group,[5,10]},
    {group,[6,6]},{group,[6,7]},{group,[6,8]},{group,[6,9]},{group,[6,10]},
    {group,[7,7]},{group,[7,8]},{group,[7,9]},{group,[7,10]},
    {group,[8,8]},{group,[8,9]},{group,[8,10]},
    {group,[9,9]},{group,[9,10]},
    {group,[10,10]}
  ],
  15 = maximize_bxor(GROUPS, 0),
  success.

erlang longpoll.erl

longpoll.erl
send(msg, date) ->
    DB.add(msg, date)

poll(lastMsgDate) ->
   return DB.getAll.filter( _.data > lastMsgDate)

erlang 用Erlang编写的对示例(参见Haskell版本)#erlang

用Erlang编写的对示例(参见Haskell版本)#erlang

pairs.erl
-module(pairs).
-export([main/0]).

%%%% 
%% Counting characters in strings
%%%%

%% Count number of occurences of C in X.
count_char_in_string(C, X) -> length([Ch || Ch <- X,
				      Ch == C]).

%% Return a list containing the count of each character in Chars for a single name.
count_chars(_, []) ->
    [0];
count_chars([], _) ->
    [0];
count_chars(Chars, Str) ->
    [count_char_in_string(string:to_upper(C), string:to_upper(Str)) || C <- Chars].

%% Count how many occurences of each character in Ch is for every name in the list.
count(_, []) ->
    [];
count(Ch, [H|T]) ->
    [count_chars(Ch, H)] ++ count(Ch, T).

%%%% 
%% Doing calculations
%%%%

%% Creates a list by summing every pair, e.g.
%% [1,2,3,4] -> [3,5,7].
sum_by_pairs([Head|Tail]) ->
    sum_by_pairs(Head, Tail).
sum_by_pairs(_, []) ->
    [];
sum_by_pairs(Head, [TailFirst|Rest]) ->
    [case Head+TailFirst<10 of
	 true -> Head + TailFirst;
	 false -> Head + TailFirst - 9 end] ++ sum_by_pairs([TailFirst|Rest]).
    
%% Counts value for a single name pair.

count_one([]) ->
    0;
count_one([_]) ->
    0;
count_one([Head, Tail]) ->
    Head * 10 + Tail;
count_one([Head|Tail]) ->
    count_one(sum_by_pairs([Head|Tail])).

%% Counts all the values for a the first name on the list.
count_for_one(_, []) ->
    [];
count_for_one(Head, [Second|Rest]) ->
    V = [count_one(lists:zipwith(fun(X,Y) -> X + Y end, Head, Second))],
    V ++ count_for_one(Head, Rest).

%% Goes through all the name combinations.
count_for_all([]) ->
    [];
count_for_all([Head|Tail]) ->
    [count_for_one(Head, Tail)] ++ count_for_all(Tail).

%%%%
%% Main logic
%%%%

%% Calculate how many of the pairs have a percentage greater or equal to Filt.
get_count(Filt, Chs, Lst) ->
    Char_counts = count(Chs, Lst),
    V = lists:filter(fun(X) -> X >= Filt end, lists:flatten([X || X <- count_for_all(Char_counts)])),
    length(V).

main() ->
    R = get_count(99, "pairs", readlines("nimet.txt")),
    io:fwrite("~w~n", [R]).


%%%%
%% File management
%%%%

%% Open a file and return a list of all of the lines in it 
%% in a list.
readlines(Filename) ->
    {ok, Device} = file:open(Filename, [read]),
    get_all_lines(Device, []).

get_all_lines(Device, Accum) ->
    case io:get_line(Device, "") of
	eof -> file:close(Device), Accum;
	Line -> get_all_lines(Device, Accum ++ [Line])
    end.
	     

erlang 改进版的test_tcp

改进版的test_tcp

test_tcp.erl
-module(test_tcp).

-export([run_tcp/3, recv_tcp/3, send_tcp/4]).

-define(SOCKET_OPTS, [{active, false}, binary, {delay_send, true}, {packet, 4}]).

run_tcp(Port, P, N) ->
    spawn_link(fun() ->
        recv_tcp(Port, P, N)
    end),
    timer:sleep(1000),
    send_tcp(localhost, Port, P, N).

recv_tcp(Port, P, N) ->
    {ok, ListenSocket} = gen_tcp:listen(Port, ?SOCKET_OPTS),
    lists:foreach(fun(Idx) ->
        spawn_monitor(fun() ->
            {ok, Socket} = gen_tcp:accept(ListenSocket),
            io:format("receiving ~p/~p~n", [Idx, P]),
            ok = inet:setopts(Socket, [{active, 10000}]),
            recv_n(Socket, N),
            io:format("receiving ~p/~p done~n", [Idx, P]),
            ok = gen_tcp:close(Socket)
        end)
    end, lists:seq(1, P)),
    waitdown(P),
    io:format("closing listen socket~n"),
    ok = gen_tcp:close(ListenSocket).

recv_n(_, 0) -> ok;
recv_n(Socket, N) ->
    receive
      {tcp, Socket, _} -> recv_n(Socket, N-1);
      {tcp_passive, Socket} ->
         ok = inet:setopts(Socket, [{active, 10000}]),
         recv_n(Socket, N);
      {tcp_closed, Socket} ->
        io:format("Closed!~n"),
        exit(closed);
      Otherwise ->
        io:format("Unknown: ~p~n", [Otherwise])
    end.

send_tcp(Host, Port, P, N) ->
    lists:foreach(fun(Idx) ->
        spawn_monitor(fun() ->
            {ok, Socket} = gen_tcp:connect(Host, Port, ?SOCKET_OPTS),
            io:format("sending ~p/~p~n", [Idx, P]),
            send_n(Socket, N),
            io:format("sending ~p/~p done~n", [Idx, P]),
            ok = gen_tcp:close(Socket)
        end)
    end, lists:seq(1, P)),
    waitdown(P).

send_n(_, 0) -> ok;
send_n(Socket, N) ->
    gen_tcp:send(Socket, term_to_binary(N)),
    send_n(Socket, N-1).

waitdown(0) -> ok;
waitdown(Count) ->
    receive
        {'DOWN', _, process, _, normal} ->
            waitdown(Count-1)
    end.

erlang 二郎。平行地图

二郎。平行地图

plists.erl
-module(plists).
-export([pmap/2,pforeach/2,npforeach/2, parmap/2]).

%%% Map

pmap(F, L) ->
  S = self(),
  Pids = lists:map(fun(I) -> spawn(fun() -> pmap_f(S, F, I) end) end, L),
  pmap_gather(Pids).

pmap_gather([H|T]) ->
  receive
    {H, Ret} -> [Ret|pmap_gather(T)]
  end;
pmap_gather([]) ->
  [].

pmap_f(Parent, F, I) ->
  Parent ! {self(), (catch F(I))}.


%%% Foreach

pforeach(F, L) ->
  S = self(),
  Pids = pmap(fun(I) -> spawn(fun() -> pforeach_f(S,F,I) end) end, L),
  pforeach_wait(Pids).

pforeach_wait([H|T]) ->
  receive
    H -> pforeach_wait(T)
  end;
pforeach_wait([]) -> ok.

pforeach_f(Parent, F, I) ->
  _ = (catch F(I)),
  Parent ! self().

npforeach(F, L) ->
  S = self(),
  Pid = spawn(fun() -> npforeach_0(S,F,L) end),
  receive Pid -> ok end.

npforeach_0(Parent,F,L) ->
  S = self(),
  Pids = pmap(fun(I) -> spawn(fun() -> npforeach_f(S,F,I) end) end, L),
  npforeach_wait(S,length(Pids)),
  Parent ! S.

npforeach_wait(_S,0) -> ok;
npforeach_wait(S,N) ->
  receive
    S -> npforeach_wait(S,N-1)
  end.

npforeach_f(Parent, F, I) ->
  _ = (catch F(I)),
  Parent ! Parent.

%%% Map list

parmap(F, L) ->
  Parent = self(),
  [receive {Pid, Result} -> Result end || Pid <- [spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]].

erlang Python / Twisted vs Erlang / OTP

Python / Twisted vs Erlang / OTP

linereceiver.erl
-module(linereceiver).
-export([start/1]).

sleep(T) ->
    receive
       after T ->
           true
    end.

start(Port) ->
    spawn(fun() ->
            start_parallel_server(Port),
            sleep(infinity)
          end).

start_parallel_server(Port) ->
    {ok, Listen} = gen_tcp:listen(Port, [binary, {packet,line},{reuseaddr, true},{active, true}]),
    spawn(fun() -> par_connect(Listen)end).

par_connect(Listen) ->
    {ok, Socket} = gen_tcp:accept(Listen),
    spawn(fun() -> par_connect(Listen) end),
    inet:setopts(Socket, [{packet, line}, list, {nodelay, true}, {active, true}]),
    io:format("Connection Made!~n"),
    get_line(Socket).

get_line(Socket) ->
    receive
        {tcp, Socket, Line} ->
            io:format("Received Line:~p~n", [Line]),
            get_line(Socket);
        {tcp_closed, Socket} ->
            io:format("Connection Closed!~n"),
            void
    end.

erlang 在Erlang的Bonjour / Zeroconf(至少是一个开始)

在Erlang的Bonjour / Zeroconf(至少是一个开始)

zeroconf.hrl
-record(dns_header, 
    {
     id = 0,       %% ushort query identification number 
     %% byte F0
     qr = 0,       %% :1   response flag
     opcode = 0,   %% :4   purpose of message
     aa = 0,       %% :1   authoritive answer
     tc = 0,       %% :1   truncated message
     rd = 0,       %% :1   recursion desired 
     %% byte F1
     ra = 0,       %% :1   recursion available
     pr = 0,       %% :1   primary server required (non standard)
                   %% :2   unused bits
     rcode = 0     %% :4   response code
    }).
-record(dns_rec,
    {
     header,       %% dns_header record
     qdlist = [],  %% list of question entries
     anlist = [],  %% list of answer entries
     nslist = [],  %% list of authority entries
     arlist = []   %% list of resource entries
    }).

-record(dns_query,
    {
     domain,     %% query domain
     type,        %% query type
     class      %% query class
     }).
zeroconf.erl
-module(zeroconf).
-include("zeroconf.hrl").

-export([open/0,start/0]).
-export([stop/1,receiver/0]).
-export([send/1]).

-define(ADDR, {224,0,0,251}).
-define(PORT, 5353).

open() ->
   {ok,S} = gen_udp:open(?PORT,[{reuseaddr,true}, {ip,?ADDR}, {multicast_ttl,4}, {multicast_loop,false}, binary]),
   inet:setopts(S,[{add_membership,{?ADDR,{0,0,0,0}}}]),
   S.

close(S) -> gen_udp:close(S).

start() ->
   S=open(),
   Pid=spawn(?MODULE,receiver,[]),
   gen_udp:controlling_process(S,Pid),
   {S,Pid}.

stop({S,Pid}) ->
   close(S),
   Pid ! stop.

receiver() ->
   receive
       {udp, _Socket, IP, InPortNo, Packet} ->
           io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]),
           receiver();
       stop -> true;
       AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]),
           receiver()
   end.

erlang 在Erlang的计数器

在Erlang的计数器

counter.erl
-module(counter).
-export([inc/1,inc/2,dec/1,dec/2,current/1,reset/1,start/1,loop/1]).

start(Name) ->
   register(Name,spawn(counter,loop,[0])),
   ok.

inc(Name, Amount) ->
    Name ! {inc_counter, Amount},
    current(Name).

inc(Name) ->
   inc(Name, 1).

dec(Name, Amount) ->
    Name ! {dec_counter, Amount},
    current(Name).

dec(Name) ->
   dec(Name, 1).

current(Name) ->
   Name ! {get_counter, self()},
   receive
       { counter_value, Count } ->
           Count
   end.

reset(Name) ->
    Name ! reset,
    current(Name).

loop(Counter) ->
   receive
       {inc_counter, Amount} ->
           NewCounter = Counter + Amount;
       {dec_counter, Amount} ->
           NewCounter = Counter – Amount;
       {get_counter, Pid} ->
           Pid ! { counter_value, Counter },
           NewCounter = Counter;
       reset ->
           NewCounter = 0
   end,
   loop(NewCounter).

erlang 如何从Erlang获取以毫秒为单位的时间戳

如何从Erlang获取以毫秒为单位的时间戳

timestamp_in_ms.erl
% gets a timestamp in ms from the epoch
get_timestamp() ->
    {Mega,Sec,Micro} = erlang:now(),
    (Mega*1000000+Sec)*1000000+Micro.

erlang Erlang中的Bonjour / Zeroconf通过订阅缓存响应

Erlang中的Bonjour / Zeroconf通过订阅缓存响应

inet_mdns.erl
-module(inet_mdns).
-include_lib("kernel/src/inet_dns.hrl").

-export([open/2,start/0]).
-export([stop/1,receiver/1]).
-export([subscribe/2,unsubscribe/2,getsubs/1]).

% gets a timestamp in ms from the epoch
get_timestamp() ->
    {Mega,Sec,Micro} = erlang:now(),
    (Mega*1000000+Sec)*1000000+Micro.

open(Addr,Port) ->
   {ok,S} = gen_udp:open(Port,[{reuseaddr,true},{ip,Addr},{multicast_ttl,4},{broadcast,true}, binary]),
   inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]),
   S.

close(S) -> gen_udp:close(S).

start() ->
   S=open({224,0,0,251},5353),
   Pid=spawn(?MODULE,receiver,[dict:new()]),
   gen_udp:controlling_process(S,Pid),
   {S,Pid}.

stop({S,Pid}) ->
   close(S),
   Pid ! stop.

subscribe(Domain,Pid) ->
    Pid ! {sub,Domain}.

unsubscribe(Domain,Pid) ->
    Pid ! {unsub,Domain}.

getsubs(Pid) ->
    Pid ! {getsubs,self()},
    receive
        {ok,Sub} ->
            {ok,Sub}
    end.

receiver(Sub) ->
  receive
      {udp, _Socket, _IP, _InPortNo, Packet} ->
          NewSub = process_dnsrec(Sub,inet_dns:decode(Packet)),
          receiver(NewSub);
      {sub,Domain} ->
          receiver(dict:store(Domain,dict:new(),Sub));
      {unsub,Domain} ->
          receiver(dict:erase(Domain, Sub));
      {getsubs,Pid} ->
          Pid ! {ok,Sub},
          receiver(Sub);
      stop -> 
           true;
       AnythingElse -> 
           io:format("RECEIVED: ~p~n",[AnythingElse]),
           receiver(Sub)
   end.

% process the dns resource records list
process_dnsrec(_Sub,{error,E}) -> 
    io:format("Error: ~p~n", [E]);
process_dnsrec(Sub,{ok,#dns_rec{anlist=Responses}}) -> 
    process_dnsrec1(Sub,Responses).

% test to see if a dns_rr.domain is subscribed to
is_subscribed(_,[]) -> false;
is_subscribed(Dom,[S|Rest]) ->
    case lists:suffix(S,Dom) of
        true ->
            {ok,S};
        false ->
            is_subscribed(Dom,Rest)
    end.

% process the list of resource records one at a time
process_dnsrec1(Sub,[]) -> Sub;
process_dnsrec1(Sub,[Response|Rest]) ->
  Dom = Response#dns_rr.domain,
  Key = {Response#dns_rr.domain,Response#dns_rr.type,Response#dns_rr.class},
  case is_subscribed(Dom,dict:fetch_keys(Sub)) of
      {ok,SD} ->
          {ok,Value} = dict:find(SD,Sub),
          % if the ttl == Zero then we forget about the details for that server
          case Response#dns_rr.ttl == 0 of
              true ->
                  NewSub = dict:store(SD,dict:new(),Sub),
                  process_dnsrec1(NewSub,[]);
              false ->
                  % update the dns_rr to the current timestamp 
                  NewRR = Response#dns_rr{tm=get_timestamp()},
                  NewValue = dict:store(Key,NewRR,Value),
                  NewSub = dict:store(SD,NewValue,Sub),
                  process_dnsrec1(NewSub,Rest)
          end;
     false ->
          process_dnsrec1(Sub,Rest)
  end.