SHARE
TWEET

Permutation

a guest Dec 27th, 2011 100 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env escript
  2.  
  3. -module(golf).
  4. -export([ pickholes/1, main/1 ]).
  5.  
  6. pick( _,           Res,         _,   _, Ts, Ts ) -> Res;
  7. pick( [{I,X} | T], Res, {X, Y, Z}, Rem, Rs, Ts ) -> pick( T, [{I,X} | Res], {0,Y,Z}, Rem, Rs+1, Ts );
  8. pick( [{I,Y} | T], Res, {X, Y, Z}, Rem, Rs, Ts ) -> pick( T, [{I,Y} | Res], {X,0,Z}, Rem, Rs+1, Ts );
  9. pick( [{I,Z} | T], Res, {X, Y, Z}, Rem, Rs, Ts ) -> pick( T, [{I,Z} | Res], {X,Y,0}, Rem, Rs+1, Ts );
  10. pick( L,           Res, {0, 0, 0}, Rem, Rs, Ts ) -> pick( L++Rem, Res, {}, [], Rs, Ts );
  11. pick( [H | T],     Res,        {},  [], Rs, Ts ) -> pick( T, [H | Res], {}, [], Rs+1, Ts );
  12. pick( [H | T],     Res,      Slot, Rem, Rs, Ts ) -> pick( T, Res, Slot, [H|Rem], Rs, Ts ).
  13.    
  14. %% API
  15. pickholes(L) -> pick( shuffle(L), [], {3,4,5}, [], 0, 6 ).
  16.  
  17. %% -- Entry point
  18. main( _ ) ->
  19.     random:seed( now() ),
  20.     erlang:display( pickholes( ootygame() ) ).
  21.  
  22. %% -- Sample data
  23. ootygame() ->
  24.     [{1,  5}, {2,  3}, {3,  4}, {4,  4}, {5,  5}, {6,  4}, {7,  3},
  25.      {8,  4}, {9,  3}, {10, 4}, {11, 3}, {12, 4}, {13, 4}, {14, 3},
  26.      {15, 4}, {16, 5}, {17, 4}, {18, 4}].  
  27.  
  28. %% Knuth / Fisher - Yates shuffle algorithm
  29. shuffle(List) ->
  30.     randomize(round(math:log(length(List)) + 0.5), List).
  31.  
  32. randomize(1, List) -> randomize(List);
  33. randomize(T, List) ->
  34.     lists:foldl( fun(_E, Acc) -> randomize(Acc) end,
  35.                  randomize(List),
  36.                  lists:seq(1, (T - 1))
  37.                ).
  38. randomize(List) ->
  39.     D = lists:map( fun(A) -> {random:uniform(), A} end, List ),
  40.     {_, D1} = lists:unzip(lists:keysort(1, D)),
  41.     D1.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top