Stylo
Stylo

Reputation: 250

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!

Upvotes: 0

Views: 3036

Answers (1)

N.W.
N.W.

Reputation: 373

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

Upvotes: 2

Related Questions