如何仅使用特定数字生成随机数,例如[1234] [4213] [3124] [英] How to generate random numbers using only specific digits, e.g [1234] [4213] [3124]

查看:70
本文介绍了如何仅使用特定数字生成随机数,例如[1234] [4213] [3124]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VB.NET中,我试图找出如何精确地使用特定数字生成固定长度的数字.

In VB.NET I am trying to figure out how exactly to generate numbers of a fixed length using specific digits.

我已经看到这些问题,但它们并不能满足我的需求:
如何在Java中的特定范围内生成随机整数?
使用C#产生范围内的随机数
如何生成特定长度的随机数python
生成随机字符串数组
生成9位数字的随机数,包括前导零

I have seen these questions but they do not cover what I am looking for:
How do I generate random integers within a specific range in Java?
Produce a random number in a range using C#
How to generate random number with the specific length in python
Generating an array of random strings
Generation 9 digits random number including leading zero

我正在尝试仅使用 1、2、3和4生成4位数字.
就像这样:

I am trying to generate 4 digit numbers using only 1, 2, 3, and 4.
It would be like this:

1234  
2134  
3124  
2143  
2431  
2413  

等...
有人可以向我解释如何实现吗?

etc...
Can someone explain to me how this can be achieved?

推荐答案

正如评论所指出的,该帖子留下了几个问题.就目前而言, Random 并没有多大关系.听起来像,您想要由这四个数字组成的 N 个值,每个数字使用一次.这是 Permutation 的起点,它来自Bjørn-RogerKringsjå的一个很好的答案,以创建列表的数字组合(一定要对其进行投票).

As the comments note, the post leaves open several questions. As it stands there is not really much to do with Random. It sounds like you want N values made from those four digits, using each one once. The starting point this Permutation class from a great answer by Bjørn-Roger Kringsjå to create a list of the combinations of the digits (be sure to upvote it).

Dim Combos = Permutation.Create("1234".ToCharArray())

Dim intVals = Combos.ConvertAll(Of Int32)(Function(s) Int32.Parse(s)).
            OrderBy(Function(r) RNG.Next()).
            ToArray()

  • 第一部分得到24个元素的组合,然后
  • 将结果转换为整数
  • 然后将顺序随机化并将其放入数组中.
  • 如果您不是指值",而是字符串(指的是具有长度的值,听起来更像是数字字符串),则只需跳过 ConvertAll 步骤.如果只需要几个,则可以在 OrderBy 之后添加 .Take(5),以仅抓取5个(例如).

    If you didn't mean "values" but strings (referring to values having a length sounds more like strings of numerals), just skip the ConvertAll step. If you only need a few, you can add .Take(5) after OrderBy to grab only 5 (for example).

    就个人而言,由于只有24种可能的(非重复)组合,因此我将它们作为数组粘贴到代码中,并以其为起点,除非"1234"部分是动态的

    Personally, since there are only 24 possible (non repeating) combinations, I'd paste them into the code as an array and use that as the starting point unless the "1234" part is dynamic.

    另请参阅:

    这篇关于如何仅使用特定数字生成随机数,例如[1234] [4213] [3124]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆