% random list exercises % deps % code rnprint(0). rnprint(N) :- random(0,10,X), write(X),nl, M is N-1, rnprint(M). % Yes rnlist(0,[]). rnlist(N,X) :- M is N-1, rnlist(M,A), random(0,10,B), append(A,[B],X). % Yes count(_,[],0). count(N,[H|T],X) :- N = H, count(N,T,Out), X is Out + 1. count(N,[H|T],X) :- not(N = H), count(N,T,X). % Yes counthelper(_,10,_,0). counthelper(Freq,Num,List,Out) :- Inc is Num + 1, Inc < 11, counthelper(Freq,Inc,List,C), count(Num,List,M), M = Freq, Out is C + 1. counthelper(Freq,Num,List,Out) :- Inc is Num + 1, Inc < 11, counthelper(Freq,Inc,List,Out). % Yes singleton_count(List,X) :- counthelper(1,0,List,X). % Yes doubleton_count(List,X) :- counthelper(2,0,List,X). % Yes rnexclusion(List,X) :- random(0,10,C), not(member(C,List)), X = C. rnexclusion(List,X) :- rnexclusion(List,X). rnsequence(List) :- rnsh(0,List). rnsh(N,[]) :- N > 9. rnsh(N,List) :- N < 10, M is N+1, rnsh(M,C), rnexclusion(C,P), append([P],C,List). % Yes iota(0,[]). iota(N,List) :- M is N-1, iota(M,L), append(L,[N],List). % Yes sum(0,[]). sum(N,List) :- N > 9, random(1,10,R), P is N-R, sum(P,C), append([R],C,List). sum(N,List) :- N < 10, M is N+1, random(1,M,R), P is N-R, sum(P,C), append([R],C,List). % Yes removeAll(_,[],[]). removeAll(N,[N|T],Out) :- removeAll(N,T,Out). removeAll(N,[H|T],Out) :- not(N=H), removeAll(N,T,C), append([H],C,Out). % Yes factors(N,[]) :- N < 1. factors(N,List) :- N > 0, M is N-1, factorh(N,M,L), append(L,[N],List). factorh(_,0,[]). factorh(N,It,List) :- 0 is N mod It, Next is It-1, factorh(N,Next,C), append(C,[It],List). factorh(N,It,List) :- not(0 is N mod It), Next is It-1, factorh(N,Next,List). % wow whats this stuff addNumber(In,Out) :- random(0,10,R), append(In,[R],Out). experiment --> addNumber, addNumber, addNumber. experiment2 --> experiment, experiment, experiment, singleton_count. help :- write('List Processing Exercise'),nl, write('Available predicates:'),nl, write(' rnprint(N) - writes N random numbers'),nl, write(' rnlist(N,List) - creates a List with N random numbers'),nl, write(' count(N,List,F) - returns F, the number of appearances of N in List'),nl, write(' singleton_count(List,F) - returns F, the number of single-appearing numbers in List'),nl, write(' doubleton_count(List,F) - returns F, the number of twice-appearing numbers in List'),nl, write(' rnexclusion(List,N) - returns N, a random number from 0 to 9 inclusive that is not a member of List'),nl, write(' rnsequence(List) - returns List, a list of 10 numbers from 0 to 9 inclusive in random order'),nl, write(' iota(N,List) - returns List, a list counting from 1 to N, or an empty list if N=0'),nl, write(' sum(N,List) - returns List, a list of elements with a sum equal to N'),nl, write(' removeAll(N,List,Out) - returns Out, the List with all elements N removed'),nl, write(' factors(N,List) - returns List, a list of all the factors of N'),nl. % init :- help.