繁体   English   中英

数组C#中的上一个索引

[英]Previous index in an array c#

我有这样初始化的数组:

int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};

然后,我有一个for()循环,每次使用以下命令在数组中搜索最大值:

int maxValue = myArray.Max();
int maxIndex = myArray.ToList().IndexOf(maxValue);

很明显,它一直在寻找9作为最高值。

我希望它首先将先前索引的值设置为低于当前maxValue但高于-1的随机值,然后继续在数组中搜索下一个maxValue并将其打印到控制台。

(如果所有值都达到一个值== 0,那么模拟将停止)<-我知道这部分。

这可能吗? 如果是这样,怎么办?

我想这可能就是您想要的。 让我知道它如何为您服务。

using System;
using System.Linq;

public class Program
{
    private static Random random = new Random();

    public static void Main()
    {
        int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
        Simulate(myArray);

    }

    static void Simulate(int[] myArray)
    {
        int maxValue = myArray.Max();
        Console.WriteLine(string.Join(" ",myArray));
        var continueSimulation = true;
        do{

            int maxIndex = myArray.ToList().IndexOf(maxValue);
            var randomValue = random.Next(0, maxValue);
            myArray[maxIndex] = randomValue;

            maxValue = myArray.Max();
            if (maxValue == 0)
                continueSimulation = false;

            Console.WriteLine(string.Join(" ",myArray));

        }while(continueSimulation);
    }
}

您可以在这个小提琴上查看一下。

希望这可以帮助!

如果要查找第二个最大值,则可以标记第一个最大值,然后继续相同的方法。 怎么办? 1-用与要查找最大值的数组长度相同的长度初始化布尔数组,然后找到第一个最大值,并用true标记第二个数组中的该位置,如果要第二个最大值,则循环遍历数组要求最大值,以及是否在第二个布尔数组中未标记该元素。 最终,您将获得第二个最大值。 另一个想法是将值取到列表中,一旦找到最大值,就从列表中删除最大值以继续相同的算法,但数组值较少

static int Max(int [] num)
{
    int max = num[0];

    for(int i = 0; i < num.Length; i ++)
    {
        if(num[i] > max)
            max = num[i];
    }

    return max;
}

static int SecondMax(int[]a)
{
    if(a.Length < 2) throw new Exception("....");

    int count = 0; 
    int max = Max(a);
    int[]b = new int[a.Length];

    for(int i = 0; i < a.Length; i ++)
    {
        if(a[i] == max && count == 0)
        {
            b[i] = int.MinValue; 
            count ++;
        }
        else b[i] = a[i];
    }

    return Max(b);
 }

老实说,这个问题有点不寻常,因此,如果您分享尝试这样做的原因,也许有人会建议一种更好的方法。 但是,要回答您的原始问题,您只需使用.NET的随机数生成器即可。

    int[] myArray = new int[] { 9, 8, 7, 3, 4, 5, 6, 2, 1 };
    Random random = new Random();

    for (int max = myArray.Max(); max > 0; max = myArray.Max())
    {
        int index = myArray.IndexOf(max);

        DoSomething(max);

        myArray[index] = random.Next(0, max);
    }

RandomMSDN doco来看,上限是互斥的,这意味着它将生成0到max-1之间的随机数,除非max == 0,在这种情况下它将返回0。

暂无
暂无

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

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