简体   繁体   English

将数字转换为 Prolog 中的列表?

[英]Convert numbers to list in Prolog?

I have created a random binary generator but it's "output" are written numbers, how i can make them a list?我创建了一个随机二进制生成器,但它的“输出”是书面数字,我怎样才能让它们成为一个列表?

bin_gen(0). bin_gen(0)。 bin_gen(Y):- random(0,2,S),write(S),Y1 is Y - 1,bin_gen(Y1). bin_gen(Y):- 随机(0,2,S),write(S),Y1 是 Y - 1,bin_gen(Y1)。

Y is the length. Y 是长度。 I want for example the output 1011 to be [1,0,1,1] after the bin_gen(0).例如,我希望 output 1011 在 bin_gen(0) 之后成为 [1,0,1,1]。

Decimal to Binary:十进制转二进制:

Conversion steps:转换步骤:

Divide the number by 2.将数字除以 2。

Get the integer quotient for the next iteration.获取下一次迭代的 integer 商。

Get the remainder for the binary digit.获取二进制数字的余数。

Repeat the steps until the quotient is equal to 0.重复上述步骤,直到商等于 0。

十进制转二进制

Prolog Code: Prolog 代码:

decimal_binary(Dec,Binary):-
(   Dec=0 ->                 %If Decimal is 0 then return Binary 0
    write('Binary = [0]');   %Else
decimal_binary1(Dec,Binary1), % Get Binary List
reverse(Binary1,Binary),!). %Reverse the Binary List

decimal_binary1(0,[]). %Base Case: Stop when Quotient is 0.
decimal_binary1(Dec,[Remainder|List]):- %Generate Binary List till Base Case succeeds
  divmod(Dec,2,Quotient,Remainder), %Built-in to get Quotient and Remainder
  decimal_binary1(Quotient,List).
    
divmod(Dividend, Divisor, Quotient, Remainder) :- %Built-in to get Quotient and Remainder
  Quotient  is Dividend div Divisor,
  Remainder is Dividend mod Divisor.

Examples:例子:

?- decimal_binary(13,Binary)
Binary = [1, 1, 0, 1]

?- decimal_binary(126,Binary)
Binary = [1, 1, 1, 1, 1, 1, 0]

?- decimal_binary(75,Binary)
Binary = [1, 0, 0, 1, 0, 1, 1]

?- decimal_binary(0,Binary)
Binary = [0]

Given an integer, you can convert it to a list of digits by repeatedly dividing by 10, taking the remainder as the ones place digit, and using the rounded down result for the next iteration:给定一个 integer,您可以通过重复除以 10 将其转换为数字列表,将余数作为个位数字,并使用向下舍入的结果进行下一次迭代:

list_digits(Int, Digits) :-
    list_digits_aux(Int, [], Digits).
list_digits_aux(Int, Digits, [Int|Digits]) :- Int < 10.
list_digits_aux(Int, Digits, Acc) :-
    NextInt is Int div 10,
    NextInt > 0,
    D is Int rem 10,
    list_digits_aux(NextInt, [D|Digits], Acc).

In this code, we use an auxiliary predicate with an accumulator argument, so that we don't have to reverse the result at the end.在这段代码中,我们使用带有累加器参数的辅助谓词,这样我们就不必在最后反转结果。

However, iiuc, if you want the list of digits, you can just tweak your current predicate slightly to construct the list of digits, rather than printing out each digit:但是,iiuc,如果你想要数字列表,你可以稍微调整你当前的谓词来构造数字列表,而不是打印出每个数字:

bin_gen(0, []).
bin_gen(Y, [D|Digits]) :-
    random(0,2,D),
    succ(Y1, Y),
    bin_gen(Y1, Digits).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM