如何在if语句中替换数组元素? C#

时间:2018-04-14 03:08:52

标签: c#

这是我已经完成的第二个版本的代码,因为第一个版本运行得太快,Random函数无法正常工作。我试图确保没有任何随机生成的数字是相同的,如果它们在数组中替换它们但它不让我调用数组。有人能告诉我我做错了吗?

using System;
using System.Timers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        public static Timer aTimer;

        static void Main(string[] args)
        {
            //Create three different random integers and store them
            Random rnd = new Random();
            int RandA = rnd.Next(0, 26);
            int RandB = rnd.Next(0, 26);
            int RandC = rnd.Next(0, 26);

            //Turn those three variables into an array
            int[] RandArray = { RandA, RandB, RandC };

            //Make sure there are no duplicates
            if (RandArray[0] == RandArray[1])
            {
                int RandArray[0] = rnd.Next(0, 26);
            }
            if (RandArray[1] == RandArray[2])
            {
                int RandArray[1] = rnd.Next(0, 26);
            }
            if (RandArray[2] == RandArray[0])
            {
                int RandArray[2] = rnd.Next(0, 26);
            }

            //Print out all three values seperately
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Value of: {1}", i, RandArray[i]);
                continue;
            }
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

好吧,我可能会改变你的方法。

public static class Randomizer
{
     private static const generator = new Random();

     public static int Generate(int minimum, int maximum) => generator.Next(minimum, maximum);
}

然后我会做以下事情:

public static class BuildRandom
{
     public IEnumerable<int> FillCollection(int capacity)
     {
          for(int index = 0; index < capacity; index++)
               yield return Randomizer.Generate(0, 26);
     }

     public static int GetRandomNumber() => Randomizer.Generate(0, 26);
}

然后我会简单地执行以下操作。

// Build Collection
var randomized = BuildRandom.FillCollection(5);

// Remove Duplicates
var filter = randomized.Distinct();

while(filter.Count != randomized.Count)
{
     var value = BuildRandom.GetRandomNumber();
     if(!filter.Any(number => number == value))
          filter.Concat(new { value });
}

答案 1 :(得分:0)

int RandArray[0] =是语法错误。试试RandArray[0] =