每日鍛鍊-3

-module(daily_three).

-export([combine/2]).
-export([bubble/1]).
-export([insert/1]).
-export([nine_table/0, full_table/0]).
-export([median/1]).


%% combine two ordered list
combine(L, []) -> qsort(L);
combine(L1, [H|T]) -> combine([H|L1], T).

qsort([]) -> [];
qsort([H|T]) -> qsort([X || X <- T, X < H]) 
				++ [H] ++
				qsort([X || X <- T, X > H]).


%% Bubble sort
bubble([]) -> [];
bubble(L) -> bubble(L, len(L)).

bubble(L, 0) -> L;
bubble([H|T], N) ->
	L = bubble_once(H, T),
	io:fwrite("Step~p:~p~n", [len([H|T]) - N + 1, L]),
	bubble(L, N - 1).

bubble_once(N, []) -> [N];
bubble_once(N, [H|T]) -> 
	if
		N < H ->
			[N | bubble_once(H, T)];	%% put min value left
		N >= H ->
			[H | bubble_once(N, T)]
	end.

len([]) -> 0;
len([_H|T]) -> 1 + len(T).


%% Insert sort, L1 is ordered list
insert(L) -> insert([], L).

insert(L, []) -> L;
insert(L, [H|T]) -> 
	NewList = insert_once(L, H),
	io:format("~p~n", [NewList]),
	insert(NewList, T).

insert_once([], N) -> [N];
insert_once([H|T], N) -> 
	if
		N < H ->
			[N | [H|T]];
		N >= H ->
			[H | insert_once(T, N)]
	end.


%% nine tables
%% 1*1 = 1
%% 1*2 = 2 2*2=4
%% ***
nine_table() -> nine_table(1, 1).

nine_table(9, 9) -> 
	print_end(9, 9);
nine_table(M, M) ->  
	print_end(M, M),
	nine_table(1, M + 1);
nine_table(M, N) -> 
	print_cell(M, N),
	nine_table(M + 1, N).

print_cell(M, N) -> io:format("~p*~p=~p\t", [M, N, M * N]).
print_end(M, N) -> io:format("~p*~p=~p~n", [M, N, M * N]).

%% nine table2
%% 1*1=1 1*2=2 1*3=3 .... 1*9=9
%% 2*1=2 2*2=4 2*3=6 .... 2*9=18
%% ....
full_table() -> full_table(1, 1).

full_table(9, 9) ->
	print_end(9, 9);
full_table(M, 9) ->
	print_end(M, 9),
	full_table(M + 1, 1);
full_table(M, N) ->
	print_cell(M, N),
	full_table(M, N + 1). 


%% Median number
%% 中位數指一個有序列表或數組的中間位置的數,求中位數時必須保證列表有序,
%% 如果列表長度爲奇數,中間位置的數位中位數,若列表爲偶數,中間兩個數的平均值爲中位數
median(L) -> 
	NewList = insert(L),
	Mid = do_mid(NewList),
	io:format("Median number is ~p~n", [Mid]).

do_mid(L) ->
	Len = len(L),
	if
		Len rem 2 =/= 0 ->
			Index = Len div 2 + 1,
			get(Index, L);
		Len rem 2 =:= 0 ->
			Index = Len div 2,
			Num1 = get(Index, L),
			Num2 = get(Index + 1, L),
			(Num1 + Num2)/2.0
	end.

get(_N, []) -> void;
get(1, [H|_T]) -> H;
get(N, [_H|T]) -> get(N - 1, T).


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章