Reputation: 71
I'm getting stuck on getting min value from array. every time when I run it, the minimum value is still zero. I know that the index has to go to minus one, but i just don't know how should I apply it on the code.
public class Class1 {
int[] numbers = new int[99];
public int Min() { // array gets de value thats on 0
int Min = numbers[0];
foreach(int number in numbers) { // if the number is smaller then 0.
if (number < Min) { // zero is the new number
Min = number;
}
}
return Min;
}
}
Upvotes: 7
Views: 57032
Reputation: 222582
You can easily use with Linq,
using System.Linq;
int min = numbers.Min();
Upvotes: 25
Reputation: 2455
This is an agnostic implemetation showing what Linq Min does for an array of integers behind the scenes. It is also the most optimized algorithm for the OPs request.
Notice:
Time Complexity: O(n) Auxiliary Space: O(1), as no extra space is used
public int Min(int[] numbers)
{
int min = numbers[0];
foreach (int num in numbers)
{
// if the number (num) is smaller than current iteration (min) then it is the minimum.
if (num < min)
{
min = num;
}
}
return min;
}
Upvotes: 0
Reputation: 1
the problem here is your naming convention, you have a. Min variable and a Min method
Upvotes: 0
Reputation: 8529
The problem is that you always calculate the minimum with all numbers, which includes zeroes for all the numbers you haven't added yet with the button. That's why your minimum always returns 0 right now unless you add 99 numbers. You need to change your Min
function to:
public int Min() {
int min = numbers[0];
for (int i = 0; i < index; i++) {
int number = numbers[i];
if (number < min) {
min = number;
}
}
return min;
}
As you can see, the function will now only calculate the minimum using the numbers you have added (with index below index
) and not all numbers in the numbers
array.
Upvotes: 5