簡體   English   中英

將數字轉換為 Prolog 中的列表?

[英]Convert numbers to list in Prolog?

我創建了一個隨機二進制生成器,但它的“輸出”是書面數字,我怎樣才能讓它們成為一個列表?

bin_gen(0)。 bin_gen(Y):- 隨機(0,2,S),write(S),Y1 是 Y - 1,bin_gen(Y1)。

Y 是長度。 例如,我希望 output 1011 在 bin_gen(0) 之后成為 [1,0,1,1]。

十進制轉二進制:

轉換步驟:

將數字除以 2。

獲取下一次迭代的 integer 商。

獲取二進制數字的余數。

重復上述步驟,直到商等於 0。

十進制轉二進制

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.

例子:

?- 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]

給定一個 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).

在這段代碼中,我們使用帶有累加器參數的輔助謂詞,這樣我們就不必在最后反轉結果。

但是,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