在我的应用程序中,我想生成9位数字的随机数字,以使它们独一无二。 每次运行应用程序时,应该只生成一个9位数的随机数,并且它应该是唯一的。 后来我想将这个数字及其关联的数据保存在一个.txt文件中,这样我可以在需要时检索与这个唯一数字相关的数据。 我应该如何实现这一目标?
In my application, i want to generate 9 digit random numbers such that they r unique. Only one 9 digit random number should be generated each time i run the application and it should be unique. Later i want to save this number along with its associated data in a .txt file so that i can retrive the data associated with this unique number when required. How should i achieve this?
最满意答案
你想让他们真正随机或真正独特吗? 你只能有其中之一。
如果你想让它们成为真正的随机数,那么只需从0-9中随机挑选9位数字并将它们构建成你的数字。 复制的可能性很小,特别是在大量迭代中。 不过,这将是真正的随机。
如果你希望它们是真正独特的,那么你必须将每一个存储在数据库中以确保没有重复。 如果您生成重复项,则需要重新生成或仅增加数字,然后重试。 如果这是您要查找的内容,那么尝试将值从1开始递增可能会很好。
Do you want them to be truly random or truly unique? You can only have one of these.
If you want them to be truly random, then just randomly pick 9 digits from 0-9 and construct them into your number. There will be a small chance of a duplication, especially over larger numbers of iterations. It will be truly random, though.
If you want them to be truly unique, then you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.
更多推荐
发布评论