Advertisement
ptrelford

Minesweeper Kata

May 24th, 2012
1,269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 0.71 KB | None | 0 0
  1. -module(ms).
  2. -export([score/1]).
  3.  
  4. index(XS) -> [{I,X}||{I,X}<-lists:zip(lists:seq(1,length(XS)),XS)].
  5.  
  6. score(Field) ->
  7.  Rows=string:tokens(Field,"\n"),N=length(Rows),
  8.  [FirstRow|_]=Rows,M=length(FirstRow),
  9.  Vectors=
  10.   [{-1,-1},{0,-1},{ 1,-1},
  11.    {-1, 0},       { 1, 0},
  12.    {-1, 1},{0, 1},{ 1, 1}],
  13.  At=fun(X,Y) -> Row=lists:nth(Y,Rows), lists:nth(X,Row) end,
  14.  Count=fun(FX,FY)->
  15.   Coords=[{FX+DX,FY+DY}||{DX,DY}<-Vectors],
  16.   Neighbours=[At(X,Y)||{X,Y}<-Coords,X>=1,Y>=1,X=<M,Y=<N],
  17.   Mines=[C||C<-Neighbours,C =:= $*],
  18.   length(Mines) end,
  19.  ScoreRows=
  20.   [[if
  21.     C =:= $* -> $*;
  22.     C =/= $* -> $0 + Count(X,Y)
  23.    end
  24.    ||{X,C}<-index(Row)]
  25.    ||{Y,Row}<-index(Rows)],
  26.  string:join(ScoreRows,"\n").
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement