简体   繁体   中英

Generate random number of 5 digits in Prolog

I want to generate a random number of 5 digits using assert/1 and retract/1. I already have the following code, but I don't know how to generate a number with 5 digits.

    draw :-
   % length(X, 5),
   random_between(0, 99999, X),
   assert(rnumber(X)),
   write(X).

Thank you!

You could just do the random predicate 5 times, then put it in a list. Something like this:

code(X):-
    random(0,9,Elem1),
    random(0,9,Elem2),
    random(0,9,Elem3),
    random(0,9,Elem4),
    random(0,9,Elem5),
    X = [Elem1, Elem2, Elem3, Elem4, Elem5],
    retractall(rnummer(_)),
      asserta(rnummer(X).

You can then later convert the list to a string using for example write(Elem1), write(Elem2), ...etc

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