Hi,
I found this program for finding the minimum value of an array.
Could anybody help me, how I have to change the code, so that I get
- the 3 lowest values of the array
- and the indices of the 3 lowest values of the array
Thank you.
Hi,
I found this program for finding the minimum value of an array.
Could anybody help me, how I have to change the code, so that I get
Thank you.
Sort the array, using any of the conventional approaches, and the three values you want will end up at one end of the array or the other, depending on whether you choose ascending or descending order.
The search phrase "arduino sort array" will yield useful results.
After you've found the lowest value, save it (and its index) and set that array value to a high value, and repeat 2 more times. Then restore the values.
That doesn't preserve (or find) the original indicies.
It is trivial to preserve the indices, if that is required.
Best decide how to handle identical values, while you're at it. Do you want the three lowest unique values, or if the lowest value, 0, appears 7 times, can you pick any three? If I was your instructor(big assumption, but this is a common class 'ask'), I'd be watching for that as a way to 'sort the best from the rest'.
Answer these questions:
getMin()
function?No need to sort the entire array, a partial sort would be sufficient.
int main() {
std::array<int, 32> numbers {96, 49, 26, 97, 2, 25, 83, 83, 81, 24, 67, 94, 74, 15, 89, 1, 69, 24, 6, 94, 77, 33, 52, 18, 62, 18, 99, 52, 2, 97, 54, 73};
size_t n = 3;
std::ranges::nth_element(numbers, numbers.begin() + n);
fmt::print("The {} smallest numbers are: {}\n",
n, std::views::take(numbers, n));
}
The 3 smallest numbers are: [2, 1, 2]
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.