X-Git-Url: https://git.xandkar.net/?a=blobdiff_plain;f=003%2Fsrc%2Flife.erl;h=f4b1fe56cd2a6a9a1c415e4aa64f2f21c77a9d9c;hb=704cefa6bfd9bab26938b62c14b47f4803e0cd64;hp=0e953ab40704838ce2e4b069ef7cf11e61b9b3c4;hpb=690cd0adc08a99640423c1bb627ee93aa3341c63;p=cellular-automata.git diff --git a/003/src/life.erl b/003/src/life.erl index 0e953ab..f4b1fe5 100644 --- a/003/src/life.erl +++ b/003/src/life.erl @@ -7,17 +7,17 @@ -define(CHAR_ALIVE, 111). % "o" -define(CHAR_BAR, 45). % "-" --define(INTERVAL, 100). +-define(GEN_INTERVAL, 100). --record(state, {x :: non_neg_integer() - ,y :: non_neg_integer() - ,n :: non_neg_integer() - ,bar :: string() - ,board=array:new() :: array() - ,gen_count :: non_neg_integer() - ,gen_duration :: non_neg_integer() - ,print_time :: non_neg_integer() +-record(state, {x :: non_neg_integer() + ,y :: non_neg_integer() + ,n :: pos_integer() + ,bar :: nonempty_string() + ,board :: array() + ,gen_count :: pos_integer() + ,gen_duration :: non_neg_integer() + ,print_time :: non_neg_integer() }). @@ -61,14 +61,22 @@ life_loop( end ), - {NewTime, NewBoard} = timer:tc(fun() -> next_generation(X, Y, Board) end), + {NewTime, NewBoard} = timer:tc( + fun() -> + next_generation(X, Y, Board) + end + ), + NewState = State#state{board = NewBoard ,gen_count = GenCount + 1 ,gen_duration = NewTime ,print_time = PrintTime }, - timer:sleep(?INTERVAL), + NewTimeMil = NewTime / 1000, + NextGenDelay = round(?GEN_INTERVAL - NewTimeMil), + timer:sleep(NextGenDelay), + life_loop(NewState). @@ -89,7 +97,10 @@ do_print_status(Bar, X, Y, N, GenCount, TimeMic, PrintTimeMic) -> do_print_board(Board) -> - CharLists = array:to_list( + % It seems that just doing a fold should be faster than map + to_list + % combo, but, after measuring several times, map + to_list has been + % consistently (nearly twice) faster than either foldl or foldr. + RowStrings = array:to_list( array:map( fun(_, Row) -> array:to_list( @@ -106,10 +117,10 @@ do_print_board(Board) -> ), ok = lists:foreach( - fun(CharList) -> - ok = io:format("~s~n", [CharList]) + fun(RowString) -> + ok = io:format("~s~n", [RowString]) end, - CharLists + RowStrings ).