%%% -*- mode: erlang -*-
%%% $Id: ary3.erlang,v 1.3 2001/06/18 18:39:33 doug Exp $
%%% http://www.bagley.org/~doug/shootout/
%%% from James Hague

-module(ary3).
-export([main/1]).

main() -> main(['1']).
main([Arg]) ->
    Num = list_to_integer(atom_to_list(Arg)),
    ets:new(y, [set, private, named_table]),
    clear_y_array(Num),
    X = list_to_tuple(lists:seq(1, Num)),
    repeat(X, Num, 1000),
    [{_,First}] = ets:lookup(y, 1),
    [{_,Last}]  = ets:lookup(y, Num),
    io:fwrite("~w ~w~n", [First, Last]),
    ets:delete(y),
    halt(0).

clear_y_array(0) -> ok;
clear_y_array(I) ->
    ets:insert(y, {I,0}),
    clear_y_array(I - 1).

repeat(X, N, 0) -> ok;
repeat(X, N, K) ->
    calc(X, N),
    repeat(X, N, K - 1).

calc(X, 0) -> ok;
calc(X, N) ->
    ets:update_counter(y, N, element(N, X)),
    calc(X, N - 1).