1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

第11回オフラインリアルタイムどう書く Erlang による実装

1
Posted at

http://qiita.com/items/93cde1a6b7561426a3ac
Erlangでやってみました。

線が交叉しているポイントを取得し(cross_p)、その列を入れ替えています(reorder_cols)。これをデーターの数だけ繰り返しています(foldl)。

ba.erl
-module(ba).
-export([tests/0, test/2, amida/1]).

tests() ->
  test("d6-7b-e1-9e", "740631825"), % 0
  test("6f-dd-ff-ff", "230685147"). % 41

test(Data, Expected) ->
  io:fwrite("~s -> ~s, ~w~n", [Data, Expected, amida(Data) =:= Expected]).

amida(Data) ->
  Hexes = string:tokens(Data, "-"),
  Init_cols = array:from_list("012345678"),
  array:to_list(lists:foldl(fun reorder_one_row/2, Init_cols, Hexes)).

% change column order of one row.
reorder_one_row(Hex, Cols) -> reorder_cols(Cols, cross_p(bin(Hex))).

% array(0123456789), [{0, 2}, {3, 4}] -> array(2104356789).
reorder_cols(A, [])         -> A;
reorder_cols(A, [{X, Y}|T]) -> reorder_cols(swap(A, X, Y), T).

% array(abcd), 1, 3 -> array(adcb). Indexes are zero origin.
swap(A, X, Y) ->
  Xvalue = array:get(X, A),
  Yvalue = array:get(Y, A),
  array:set(Y, Xvalue, array:set(X, Yvalue, A)).

% "d6" -> "11010110".
bin(Hex) -> integer_to_list(list_to_integer(Hex, 16), 2).

% "11010110" -> [{5, 7}, {3, 4}, {0, 2}].
cross_p(Bin)              -> cross_p(Bin ++ "0", $0, 0, []).
cross_p([], _, _, L)      -> L;
cross_p([$0|T], $0, S, L) -> cross_p(T, $0, S, L);
cross_p([$1|T], $0, _, L) -> cross_p(T, $1, 8 - length(T), L);
cross_p([$0|T], $1, S, L) -> cross_p(T, $0, 0, [{S, 8 - length(T)} | L]);
cross_p([$1|T], $1, S, L) -> cross_p(T, $1, S, L).
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?