user3872666 user3872666 - 26 days ago 7
C# Question

Previous index in an array c#

I have an array initialized as such:

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


I then have a for() loop searching the array for the highest value each time using:

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


It obviously keeps finding 9 as the highest value.

I want it to first set the previously indexed value to a randomized value below the current maxValue but above -1 and continue searching the array for the next maxValue and print it to console.

(If all values reach a value == 0 then the simulation stops) <- this part I know how to do.

Is this possible? If so, how?

Answer

I guess this might be what you want. Let me know how it works for you.

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);
    }
}

You can check it out on this fiddle.

Hope this helps!