Last active
December 18, 2015 15:28
-
-
Save pazworld/5804189 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment