序所有二进制数 [英] prolog all binary numbers

查看:92
本文介绍了序所有二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个谓词,该谓词将产生N位的所有二进制数.

i need a predicate that will produce all the binary number of N digits .

例如谓词binary(2,L)

For instance the predicate binary(2,L)

将返回L = [[0, 0], [0, 1], [1, 0], [1, 1]].

请不要使用findall ....

please do not use findall ....

推荐答案

一旦有了一个代表所有具有N位数字的列表,生成N + 1位的所有数字仅是展开每个N数字[a,b,c,...]分为两个N + 1个数字:[0,a,b,c,...][1,a,b,c,...].

Once you have a list representing all the numbers with N bits, generating all the numbers of N+1 bits is just a matter of unfolding every N-number [a,b,c,...] into two N+1-numbers: [0,a,b,c,...] and [1,a,b,c,...].

更新:

unfold([], []).
unfold([H|T], [[0|H], [1|H]|L]) :-
   unfold(T, L).

bn(N, L) :-
   (   N = 0
   ->  L = [[]]
   ;   N1 is N - 1,
       bn(N1, L1),
       unfold(L1, L)
   ).

这篇关于序所有二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆