There are different ways of doing this - it depends on what the assignment is asking for.
This is how I might do it:
Start with a two-dimensional array of integers.
This array will represent a square, which means the two sides will always be equal in length. For this reason, we only really need one constant to represent the dimensions of our square (as opposed to using 'width' and 'height').
1 2 3 4 5 6
|
const int scale = 3;
int numbers[scale][scale] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
|
Next, create a set of integers. A set is an associative container (it's kind of like a map, but it only has a key instead of a key-value pair). We'll be using this set later to keep track of which numbers can actually be the minimum number (in my example, the set will contain the numbers 4, 7 and 8). What's nice about using a set is that each of it's elements must be unique, and its elements are internally ordered from lowest to greatest by default.
std::set<int> set;
Now that we have the set, we can populate it with numbers we're interested in.
We have a for-loop that iterates through each of the rows, and a nested for-loop that iterates through elements of each row.
1 2 3 4 5
|
for (int y = 0; y < scale; ++y) {
for (int x = 0; x < y; ++x) {
set.insert(numbers[y][x]);
}
}
|
Notice how the second for-loop only executes while (x < y). With each iteration of the outer for-loop, 'y' is incremented by one, which has the following effect:
y = 0
x = 0
(x < y) is false - nothing is inserted to the set.
y = 1
x = 0
(x < y) is true - insert 'numbers[1][0]', which is 4, into the set.
y = 1
x = 1
(x < y) is false.
y = 2
x = 0
(x < y) is true - insert 'numbers[2][0]', which is 7, into the set.
y = 2
x = 1
(x < y) is true - insert 'numbers[2][1]', which is 8, into the set.
y = 2
x = 2
(x < y) is false. |
The set now contains 4, 7 and 8. These three numbers will also be ordered from lowest (4) to greatest (8). Therefore, the smallest number in that region of the square will always be the first element in the set. We can retrieve the first element of the set like so:
std::cout << "The smallest number is " << *set.begin() << "." << std::endl;
The final program might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <set>
int main() {
const int scale = 3;
int numbers[scale][scale] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
std::set<int> set;
for (int y = 0; y < scale; ++y) {
for (int x = 0; x < y; ++x) {
set.insert(numbers[y][x]);
}
}
std::cout << "The smallest number is " << *set.begin() << "." << std::endl;
return 0;
}
|