Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random List Generation

Status
Not open for further replies.

fxtdr79

Programmer
Jun 10, 2010
3
CA
Trying to write something like generate(L, N) that will generate a list L of size N where each element is either a 0 or a 1. This is what I have but it doesn't work, any suggestions?

generate(L, 0) :- !.
generate(L, N) :- A is N - 1, B is random(2), generate([B|L], A).

I also tried something like this that didn't work either

generate(L, 0) :- !.
generate(L, N) :- A is N - 1, B is random(2), append(L, B, C), generate(C, A).
 
I've modified your code a bit:

Code:
generate(L, N) :-
    generate(L, [], N).

generate(L, L, 0) :- !.
generate(L, X, N) :-
    A is N - 1,
    B is random(2),
    generate(L, [B|X], A).
 
In SWI-Prolog you can do that
Code:
generate(L, N) :-
   length(L, N),
   maplist(init, L).

init(C) :-
  C is random(2).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top