Generate random number of 5 digits in Prolog

こ雲淡風輕ζ 提交于 2019-12-24 19:33:27

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/46668250/generate-random-number-of-5-digits-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!