我不确定如何将List<int>
更改为指定的数组并返回每个元素。我试图创建返回数组的方法。
using System;
using System.Collections.Generic;
namespace RandomArray
{
public class RandomArrayNoDuplicates
{
static Random rng = new Random();
static int size = 45;
static int[] ResultArray;
static void Main()
{
int[] ResultArray = InitializeArrayWithNoDuplicates(size);
Console.ReadLine();
}
/// <summary>
/// Creates an array with each element a unique integer
/// between 1 and 45 inclusively.
/// </summary>
/// <param name="size"> length of the returned array < 45
/// </param>
/// <returns>an array of length "size" and each element is
/// a unique integer between 1 and 45 inclusive </returns>
public static int[] InitializeArrayWithNoDuplicates(int size)
{
List<int> input = new List<int>();
List<int> output;
//Initialise Input
for (int i = 0; i < size; i++)
{
input[i] = i;
}
//Shuffle the array into output
Random rng = new Random();
output = new List<int>(input.Capacity);
for (; input.Capacity > 0;)
{
int index = rng.Next(input.Capacity);
int value = input[index];
input.Remove(index);
output.Add(value);
}
return; // Returning the final array here with each element
}
}
}
是否存在List<int>
类型只使用数组的等效方法,而不是使用列表然后转换回数组?我应该使用不同的系统库参考吗?
答案 0 :(得分:1)
使用k := int16(d) - int16(r)
max_k := int16(d) + int16(r)
if k < 1 {
k = 1
}
for ; k <= max_k; k++ {
...
}
作为列表,如下所示:
.ToArray
反之亦然,您也可以使用list.ToArray();
,
答案 1 :(得分:1)
有,您可以随时手动交换两个数组元素而不使用任何列表:
public static void Swap<T>(T[] array, int i, int j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}