Shahzad Bhatti

November 2, 2007

Erlang translation of States Puzzle

Filed under: Computing — admin @ 8:48 pm

I came across neat solution from A Simple Programming Puzzle Seen Through Three Different Lenses regarding states puzzle from Mark Nelson, which was originally posted NPR. Here is translation of Anders Pearson’s solution in Erlang:

 1 -module(states).

 2

 3 %%--------------------------------------------------------------------

 4 %% External exports

 5 %%--------------------------------------------------------------------

 6 -export([

 7          test/0

 8          ]).

 9

10 states() ->

11     ["alabama","alaska","arizona","arkansas","california","colorado",

12           "connecticut","delaware","florida","georgia","hawaii","idaho",

13           "illinois","indiana","iowa","kansas","kentucky","louisiana",

14           "maine","maryland","massachusetts","michigan","minnesota",

15           "mississippi","missouri","montana","nebraska","nevada",

16           "newhampshire","newjersey","newmexico","newyork","northcarolina",

17           "northdakota","ohio","oklahoma","oregon","pennsylvania","rhodeisland",

18           "southcarolina","southdakota","tennessee","texas","utah","vermont",

19           "virginia","washington","westvirginia","wisconsin","wyoming"].

20

21 test() ->

22     States = states(),

23     Dict = dict:new(),

24     {_, _, MatchingStates} = lists:foldl(fun lookup/2, {Dict, States, []}, States),

25     [["northcarolina","southdakota"],["southcarolina","northdakota"]] = MatchingStates.

26

27 lookup(State, {Dict, States, MatchingStates}) ->

28     {State, Dict1, MatchingStates1} = lists:foldl(fun lookup2/2, {State, Dict, MatchingStates}, States),

29     {Dict1, States, MatchingStates1}.

30

31 lookup2(State1, {State2, Dict, MatchingStates}) ->

32     Key = lists:sort(lists:flatten(State1 ++ State2)),

33     Response = dict:find(Key, Dict),

34     MatchingStates1 = case Response of

35         {ok, [State2, State1] } ->

36              MatchingStates;

37         {ok, _} ->

38              [[State1, State2]|MatchingStates];

39         _ ->

40             MatchingStates

41     end,

42     Dict1= dict:store(Key, [State1, State2], Dict),

43     {State2, Dict1, MatchingStates1}.




	

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.

Powered by WordPress