随机生成一个数字列表 [英] Generate a list of numbers in random

查看:78
本文介绍了随机生成一个数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以随机顺序创建一个包含1到16的16个数字的列表。是否可以在数组中执行此操作?什么是最好的方法呢?





使用系统;



class Program

{

static void Main()

{

string [] arr = new string []

{

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

};

string [] shuffle = RandomStringArrayTool.RandomizeStrings(arr);

foreach(字符串s in shuffle)

{

Console.WriteLine(s);

}

}





我得到这个上下文中不存在RandomStringArrayTool的错误

I need to create a list of 16 numbers from 1 to 16 in random order. Is it possible to do this in an array? What would be the best way to do this?


using System;

class Program
{
static void Main()
{
string[] arr = new string[]
{
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"
"10"
"11"
"12"
"13"
"14"
"15"
"16"
};
string[] shuffle = RandomStringArrayTool.RandomizeStrings(arr);
foreach (string s in shuffle)
{
Console.WriteLine(s);
}
}


I get an error that the RandomStringArrayTool doesn't exist in this context

推荐答案

这是作业(我知道这是因为这是许多论坛中的常见问题)



家庭作业是有原因的 - 帮助你学习,所以只是给你答案会适得其反。



这里的关键是不要考虑生成1到16之间的随机数,而是随机命令数字1到16出现在数组中。



例如,您可以将所有数字放入数组中然后基于一对随机数将它们交换几次
This is homework (I know this because it is a regular question in many forums)

Homework is set for a reason - to help YOU learn, so just giving you the answer would be counter-productive.

The key thing here is not to think about generating random numbers between 1 and 16 but to randomise the order that the numbers 1 to 16 appear in the array.

So for example, you could put all of the numbers into an array and then swap them around several times based on a pair of random numbers


请阅读我对问题和解决方案2的评论。



要随机生成数字,请使用:随机类 [ ^ ]。



试试!
Please, read my comment to the question and solution2 too.

To randomly generate numbers use: Random Class[^].

Try!


喜欢这个。基于 http://stackoverflow.com/questions/273313/randomize-a-listt- in-c-sharp [ ^ ]



Like this. Based on http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp[^]

static void Main(string[] args)
{
	List<int> numbers = new List<int>();

	for(int i = 0; i < 16; i++)
	{
		numbers.Add(i);
	}

	Shuffle(numbers);
}

public static void Shuffle<T>(IList<T> list)
{
	Random rng = new Random();
	int n = list.Count;
	while (n > 1)
	{
		n--;
		int k = rng.Next(n + 1);
		T value = list[k];
		list[k] = list[n];
		list[n] = value;
	}
}


这篇关于随机生成一个数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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