jeudi 11 octobre 2018

How to solve an index out of bounds issue, when you have to take into consideration both neighbors of an array's element?

This thing that I'm writing should do the following: get as an input a number, then, that many kids' names, and that many grades. Then, assign each kid a number of coins, so that if their grade is bigger, than their neighbor's, they get more coins and vice versa. What I wrote is this:

        string input = Console.ReadLine();
        int n = Convert.ToInt32(input);
        int i = 0;
        string[] names = new string[n];
        for (i = 0; i < n; i++)
        {
            names[i] = Console.ReadLine();
        }
        string[] gradeText = new string[n];
        int[] grades = new int[n];

        for (i = 0; i < n; i++)
        {
            gradeText[i] = Console.ReadLine();
            grades[i] = Convert.ToInt32(gradeText[i]);
        }

        int[] minCoins = { 1, 2, 3 };
        int[] coinArray = new int[n];
        for (i = 1; i < n - 2; i++)
        {
            if (grades[0] > grades[1])
            {
                coinArray[0] = 3;
            }

            else
            {
                coinArray[0] = 1;
            }
            if (grades[i] > grades[i + 1] && grades[i] > grades[i - 1])
            {
                coinArray[i] = 3;
            }
            if (grades[i] > grades[i + 1] || grades[i] > grades[i - 1])
            {
                coinArray[i] = 2;
            }
            if (grades[i] < grades[i + 1] && grades[i] < grades[i - 1])
            {
                coinArray[i] = 1;
            }

            if (grades[n - 1] > grades[n - 2])
            {
                coinArray[n - 1] = 3;
            }
            else
            { coinArray[n - 1] = 1; }

        }



        for (i = 0; i < n; i++)
        {
            Console.WriteLine(names[i] + " " + coinArray[i]);
        }

I know my loop is hella messed up, but any tips on how to fix it would be kindly appreciated!

Aucun commentaire:

Enregistrer un commentaire