3

I've already written down the code for a procedure that modifies an incoming array of doubles by normalizing it. To normalize the array of numbers, I had to divide each number by the maximum value in the array. However, my code forces me to implement System.Linq

Here's my code:

public void Test9(double[] numbers)
{
    double MaximumNumber = numbers.Max();
    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers[i] / MaximumNumber;
    }
}

My question, how can I achieve the same solution without implementing using System.Linq; at the top of the program.

Zerox
  • 61
  • 5

2 Answers2

3

Go over the array and get the maximum value first (make sure to check if there are items in the array first, so check for numbers.Length > 0):

double max = numbers[0];

for (int i = 1; i < numbers.Length; i++)
{
    if (numbers[i] > max)
    {
        max = numbers[i];
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

Just find the maximum by iterating the array

public void Test9(double[] numbers)
{
    // Find the maximum without linq
    double maxNumber = double.MinValue;
    for (int i = 0; i < numbers.Length; i++)
    {
       if(numbers[i] > maxNumber) 
          maxNumber = numbers[i];
    }

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers[i] / maxNumber;
    }
}
Jcl
  • 27,696
  • 5
  • 61
  • 92