Least-Common-Multiple/main.cpp

83 lines
1.8 KiB
C++
Raw Permalink Normal View History

2020-12-03 11:43:51 -05:00
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib> // atoi
class Rate
{
public:
Rate(int rate)
: base_rate(rate), min_rate(rate)
{ }
/*
* This is the rate given to you by the user
*/
int BaseRate() const { return base_rate; }
/*
* This is the least common multiple when compared to all the other rates
*/
int MinimumRate() const { return min_rate; }
/*
* This tells you how many you'd need to build to achieve the minimum rate
*/
int QuantityToBuild() const
{
// TODO(dev): assert !(min_rate % rate), otherwise this shit's broken or not yet calculated
return min_rate / base_rate;
}
/*
* This is used to step up to the next rate
*/
void Increment() { min_rate += base_rate; }
private:
const int base_rate;
int min_rate; // needs to be incremented/calculated in the program loop
};
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::cout << "Usage: ./" << argv[0] << " rate1 rate2 [...] rateN" << std::endl;
return -1;
}
std::vector<Rate> rates;
// Add all command line parameters (rates) to the vector:
for(auto i = 1; i < argc; ++i)
rates.push_back(Rate(atoi(argv[i])));
// NOTE(dev): Run through all (2+) rates to determine the least common multiple.
// Increment each rate until they all come out to the same value
bool difference_found;
do
{
difference_found = false;
for(auto &rate : rates)
{
for(auto &other : rates) // sure it checks against itself, but this isn't optimized sooo
{
if(rate.MinimumRate() < other.MinimumRate())
{
difference_found = true;
while(rate.MinimumRate() < other.MinimumRate())
rate.Increment();
}
}
}
} while(difference_found);
for(auto rate : rates)
std::cout << rate.QuantityToBuild() << " * " << rate.BaseRate() << " == "
<< rate.MinimumRate() << std::endl;
return 0;
}