简体   繁体   中英

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(Y):- random(0,2,S),write(S),Y1 is Y - 1,bin_gen(Y1).

Y is the length. I want for example the output 1011 to be [1,0,1,1] after the bin_gen(0).

Decimal to Binary:

Conversion steps:

Divide the number by 2.

Get the integer quotient for the next iteration.

Get the remainder for the binary digit.

Repeat the steps until the quotient is equal to 0.

十进制转二进制

Prolog Code:

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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