JustPaste.it

lucky_number.txt

/* A lucky number is a 10-based number, which has at least a "6" or an "8" in its digits. 
 * However, if it has "6" and "8" at the same time, then the number is NOT lucky. 
 * For example, "16", "38", "666" are lucky numbers, while "234" , "687" are not.
 * Now we want to know how many lucky numbers (without leading zeroes)
 * are there between L and R, inclusive?
 * 
 * L is LowerBound
 * R is UpperBound
 * N is the list containing the number in the interval
 * P is the total occurence of lucky numbers
 * 
 * between_to_list -> generates all the numbers between L and R included
 * 
 * check_list -> check if the current element of the list contain 6 and
 * not contain 8, or contains 8 and not contain 6, if these constraints
 * are satisfied increment P by 1
 * 
 * query tested -> generate_interval(1,10)*/
 
generate_interval(L,R):- 
    between_to_list(L,R,N),
    P = 0,
check_list(N, P),
    write(P).
 
between_to_list(X,X,[X]) :- !.
between_to_list(X,Y,[X|Xs]) :-
    X =< Y,
    Z is X+1,
    between_to_list(Z,Y,Xs).
 
check_list([],_).
check_list([H|T],P):-
H == 6,
    H \= 8,
Z is P+1,
    check_list(T,Z);
    H == 8,
    H \= 6,
Z is P+1,
    check_list(T,Z).
 
check_list([H|T],P):- check_list(T,P).