简体   繁体   English

使用rand()生成一个没有数字重复的数字

[英]Using rand() to generate a number without digit duplicates

How can we customize the code with rand() function in order to generate a n-digit number, where n<8, without digit duplicates in it? 我们如何使用rand()函数自定义代码以生成n位数字,其中n <8,其中没有数字副本? Suppose I want to generate a 4 digit number from 1000 to 9999, this number should not contain digit duplicates: for instance 1023 4798, etc. Btw, we may not generalize n. 假设我想生成一个从1000到9999的4位数字,这个数字不应该包含数字重复:例如1023 4798等。顺便说一句,我们可能不会概括n。

Edits 编辑

I skimmed through the answers in the question I was adressed to. 我在解决的问题中略过了答案。 I honestly think that the problem of generating a sequence of digits without a single duplicate in it is in my opinion easier that generating a number with no duplicate digits. 老实说,我认为生成一系列数字而没有单个副本的问题在我看来更容易生成一个没有重复数字的数字。 Still looking for an answer. 还在寻找答案。

My code is a real mess and truthfully does not contain a single try to tackle the stated problem. 我的代码是一个真正的混乱,如实地不包含单一的尝试来解决所述的问题。 I have a paper draft but still it's based on assigning an integer variable to each digit in a number and a small loop which checks if some of them are equal and increment/decrements one of them. 我有一个论文草稿,但它仍然基于为一个数字中的每个数字分配一个整数变量和一个小循环,它检查它们中的一些是否相等并增加/减少其中一个。 This sounds like a bad idea even to me, but this is all I can come to. 这听起来对我来说是一个坏主意,但这就是我所能得到的。

You have several obvious choices: 你有几个明显的选择:

  1. Pick a random number and if it contains any repeating digits, pick again. 选择一个随机数,如果它包含任何重复数字,请再次选择。 This can get slow if n is high. 如果n很高,这可能会变慢。

  2. Shuffle the digits from 0 to 9 randomly and take the first n digits. 随机抽取数字从0到9并取前n个数字。

  3. Keep an array of the remaining digits. 保留一组剩余的数字。 Pick an element from the array randomly and remove it from the array. 从数组中随机选取一个元素并将其从数组中删除。 Repeat for the number of digits you need. 重复您需要的位数。

If zero is not a legal first digit, you will have to work around that. 如果零不是合法的第一个数字,您将不得不解决这个问题。 It should be obvious how to do that in each of these cases. 在每种情况下都应该明白如何做到这一点。 You can always just pick again if the resulting number is too low. 如果结果数字太低,您可以随时再次选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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