I need a predicate to produce all binary numbers with length N
in a list.
Sample use:
?- bins(2,L).
L = [[0,0], [0,1], [1,0], [1,1]]. % expected result
I need a predicate to produce all binary numbers with length N
in a list.
Sample use:
?- bins(2,L).
L = [[0,0], [0,1], [1,0], [1,1]]. % expected result
No need to use findall/3
!
We define bins/2
based on clpfd, foldl/4
, Prolog lambdas, if_/3
, and (#<)/3
.
:- use_module(library(lambda)).
:- use_module(library(clpfd)).
bins(N,Zss) :-
if_(N #< 1,
( N #= 0, Zss = [[]] ),
( N #= N0+1,
bins(N0,Xss),
foldl(\Bs^phrase(([[0|Bs]],[[1|Bs]])),Xss,Zss,[]))).
Sample use:
?- bins(4,Zss).
Zss = [[0,0,0,0],[1,0,0,0],[0,1,0,0],[1,1,0,0],
[0,0,1,0],[1,0,1,0],[0,1,1,0],[1,1,1,0],
[0,0,0,1],[1,0,0,1],[0,1,0,1],[1,1,0,1],
[0,0,1,1],[1,0,1,1],[0,1,1,1],[1,1,1,1]].
Here is the most general query:
?- bins(N,Zss).
N = 0, Zss = [[]]
; N = 1, Zss = [[0],[1]]
; N = 2, Zss = [[0,0],[1,0],[0,1],[1,1]]
; N = 3, Zss = [[0,0,0],[1,0,0],[0,1,0],[1,1,0],[0,0,1],[1,0,1],[0,1,1],[1,1,1]]
...
There are probably better ways, but here is a solution using findall
bins(N,L) :-
findall(Num,binary_number(N,Num),L).
binary_number(0,[]).
binary_number(N,[D|Ds]) :-
N > 0,
member(D,[0,1]),
N1 is N - 1,
binary_number(N1,Ds).
Alternatively :
member_(A, B) :- member(B, A).
bins(Size, Result) :-
findall(L, (length(L, Size), maplist(member_([0, 1]), L)), Result).
Could be simplified with the use of the lambda module :
bins(Size, Result) :-
findall(L, (length(L, Size), maplist(\X^member(X, [0, 1]), L)), Result).