MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / main

Function main

Exercises/Modules/Chapter 13/Soln13_08/Soln13_08.cpp:14–59  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12import PRNG;
13
14int main()
15{
16 const double limit {99}; // Upper limit on Box dimensions
17
18 std::random_device seeder; // True random number generator to obtain a seed (slow)
19 auto random{ PseudoRandomNumberGenerator{ static_cast<int>(seeder()) } };
20
21 const size_t boxCount {20}; // Number of Box object to be created
22 std::vector<Box> boxes; // Vector of Box objects
23
24 // Create 20 Box objects
25 for (size_t i {}; i < boxCount; ++i)
26 boxes.push_back(Box{ static_cast<double>(random()), static_cast<double>(random()), static_cast<double>(random()) });
27
28 size_t first {}; // Index of first Box object of pair
29 size_t second {1}; // Index of second Box object of pair
30 double minVolume {(boxes[first] + boxes[second]).volume()};
31
32 for (size_t i {}; i < boxCount - 1; ++i)
33 {
34 for (size_t j {i + 1}; j < boxCount; j++)
35 {
36 if (boxes[i] + boxes[j] < minVolume)
37 {
38 first = i;
39 second = j;
40 minVolume = (boxes[i] + boxes[j]).volume();
41 }
42 }
43 }
44
45 std::cout << "The two boxes that sum to the smallest volume are "
46 << boxes[first] << " and " << boxes[second] << '\n';
47 std::cout << std::format("The volume of the first box is {:.1f}\n",
48 boxes[first].volume());
49 std::cout << std::format("The volume of the second box is {:.1f}\n",
50 boxes[second].volume());
51 std::cout << "The sum of these boxes is " << (boxes[first] + boxes[second]) << '\n';
52 std::cout << std::format("The volume of the sum is {:.1f}", minVolume) << std::endl;
53
54 Box sum{ 0, 0, 0 }; // Start from an empty Box
55 for (const auto& box : boxes) // And then add all randomly generated Box objects
56 sum += box;
57
58 std::cout << "The sum of " << boxCount << " random boxes is " << sum << std::endl;
59}

Callers

nothing calls this directly

Calls 2

push_backMethod · 0.45
volumeMethod · 0.45

Tested by

no test coverage detected