1

如何在不使用 erlang shell 的情况下编译和运行此代码

我在 erlang 中有以下代码,它为 n-queens 问题提供了解决方案。它以皇后的数量作为参数。该程序在 erl shell 上成功运行。但是我需要在没有 shell 的情况下在 linux 终端上运行这个程序,以便我可以使用“时间”命令来测量程序的执行时间。

    -module(queen).
-export([queen/1]).

queen(N) ->
    IJ = [{I, J} || I <- lists:seq(1, N), J <- lists:seq(1, N)],
    lists:foreach(fun({I, J}) -> put_data(I, J, true) end, IJ),
    solve(N, 1, [], 0).

solve(N, J, Board, Count) when N < J ->
    print(N, Board),
    Count + 1;
solve(N, J, Board, Count) ->
    F = fun(I, Cnt) ->
            case get_data(I, J) of
                true  ->
                    put_data(I, J, false),
                    Cnt2 = solve(N, J+1, [I|Board], Cnt),
                    put_data(I, J, true),
                    Cnt2;
                false -> Cnt
            end
        end,
    lists:foldl(F, Count, lists:seq(1, N)).

put_data(I, J, Bool) ->
    put({row, I  }, Bool),
    put({add, I+J}, Bool),
    put({sub, I-J}, Bool).

get_data(I, J) ->
    get({row, I}) andalso get({add, I+J}) andalso get({sub, I-J}).

print(N, Board) ->
    Frame = "+-" ++ string:copies("--", N) ++ "+",
    io:format("~s~n", [Frame]),
    lists:foreach(fun(I) -> print_line(N, I) end, Board),
    io:format("~s~n", [Frame]).

print_line(N, I) ->
    F = fun(X, S) when X == I -> "Q " ++ S;
           (_, S)             -> ". " ++ S
        end,
    Line = lists:foldl(F, "", lists:seq(1, N)),
    io:format("| ~s|~n", [Line]).
4

1 回答 1

0

您可以使用计时器模块来检查执行速度:

{Time, Value} = timer:tc(queen, queen, [N])

或者您可以将代码转换为 escript:

#!/usr/bin/env escript

-mode(native). %% to fun faster

main([NStr]) ->
    N = list_to_integer(NStr),
    IJ = [{I, J} || I <- lists:seq(1, N), J <- lists:seq(1, N)],
    lists:foreach(fun({I, J}) -> put_data(I, J, true) end, IJ),
    solve(N, 1, [], 0).

solve(N, J, Board, Count) when N < J ->
    print(N, Board),
    Count + 1;
solve(N, J, Board, Count) ->
    F = fun(I, Cnt) ->
            case get_data(I, J) of
                true  ->
                    put_data(I, J, false),
                    Cnt2 = solve(N, J+1, [I|Board], Cnt),
                    put_data(I, J, true),
                    Cnt2;
                false -> Cnt
            end
        end,
    lists:foldl(F, Count, lists:seq(1, N)).

put_data(I, J, Bool) ->
    put({row, I  }, Bool),
    put({add, I+J}, Bool),
    put({sub, I-J}, Bool).

get_data(I, J) ->
    get({row, I}) andalso get({add, I+J}) andalso get({sub, I-J}).

print(N, Board) ->
    Frame = "+-" ++ string:copies("--", N) ++ "+",
    io:format("~s~n", [Frame]),
    lists:foreach(fun(I) -> print_line(N, I) end, Board),
    io:format("~s~n", [Frame]).

print_line(N, I) ->
    F = fun(X, S) when X == I -> "Q " ++ S;
           (_, S)             -> ". " ++ S
        end,
    Line = lists:foldl(F, "", lists:seq(1, N)),
    io:format("| ~s|~n", [Line]).

并使其从 linux shell 可执行:

chmod +x queue

./queue然后使用命令或从 linux shell 运行它time ./queue

于 2013-11-06T07:02:54.300 回答