%%%
%%% 目盛の消えたものさし
%%% by Naoyuki Tamura (tamura@kobe-u.ac.jp)
%%%

measure(N, M, L) :-
	part(N, M, L),
	gaps(L, Ns),
	length(Ns, N).

part(N, 1, [N]).
part(N, M, [I|L]) :-
        M >= 2,
        I1 is N-M+1,
        for(I, 1, I1),
        N1 is N-I,
        M1 is M-1,
        part(N1, M1, L).

%%
%% 測れる長さのリストを返す
%%
gaps(L, Ns) :-
	setof(N, gap(L, N), Ns).

gap(L, N) :-
	sublist(L, Xs),
	sum_list(Xs, N).

sublist(Xs, [X|Zs]) :-
	append(_, [X|Xs1], Xs),
	append(Zs, _, Xs1).

sum_list([], 0).
sum_list([X|Xs], S) :-
	sum_list(Xs, S0),
	S is S0 + X.

for(N, N, M) :- N =< M.
for(I, N, M) :- N =< M, N1 is N+1, for(I, N1, M).

append([], Z, Z).
append([W|X], Y, [W|Z]) :-
	append(X, Y, Z).

runtime(G) :-
        statistics(runtime, _),
        call(G),
        !,
	statistics(runtime, [_,T]),
	write('CPU時間 '), write(T), write(' ミリ秒'), nl.
runtime(_) :-
	statistics(runtime, [_,T]),
	write('CPU時間 '), write(T), write(' ミリ秒'), nl, fail.
