I've written a program following the instructions of an exam paper. There are no solutions available so I would appreciate a feedback. I'm concerned with main in particular (I've already posted a similar question here). I've tried to solve the problem as I've seen it's done in other solutions made available by our teacher. Also the constructors made me think a lot.
I was asked to make a program to represent destinations in a square [0,1]x[0,1], a salesman that has to go in some destinations in that square and another salesman inheriting from the former but with slightly different habits.
#include <iostream>
#include <vector>
#include <set>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
class Location {
private:
double x_, y_;
public:
Location(double x, double y) : x_(x), y_(y) { }
Location() {
x_ = drand48();
y_ = drand48();
}
Location(const Location & L) : x_(L.x_), y_(L.y_) { }
double getx() {return x_; }
bool operator<(const Location & L) { return x_ < L.x_; }
double distance(const Location & L) {
return std::sqrt(std::pow(x_ - L.x_, 2) + std::pow(y_ - L.y_, 2));
}
};
class Salesman {
private:
Location start_;
protected:
std::vector<Location> tobevisited_;
public:
Salesman(const Location & start, std::vector<Location>::iterator it1, std::vector<Location>::iterator it2) : start_(start), tobevisited_(it1, it2) { }
int ndest() { return tobevisited_.size(); }
virtual double visit() {
double dist = 0;
sort(tobevisited_.begin(), tobevisited_.end());
dist = (*(tobevisited_.begin())).distance(start_);
for(std::vector<Location>::iterator it = tobevisited_.begin()+1; it != tobevisited_.end(); it++) {
dist += (*(it)).distance(*(it-1));
}
return dist;
}
};
class LazySalesman : public Salesman {
private:
double d_;
public:
LazySalesman(double d, std::vector<Location>::iterator it1, std::vector<Location>::iterator it2) : d_(d), Salesman(Location(0,0), it1, it2) { }
double visit() {
double dist = 0;
dist = Salesman::visit();
dist += d_*ndest();
}
};
int main() {
srand48(time(NULL));
Location start(0., 0.);
Location start2(1,1);
int cont = 0;
for(int i=0; i<3000; i++) {
std::vector<Location> v;
for(int j=0; j<10; j++) {
v.push_back(Location());
}
Salesman Willy(start, v.begin(), v.end());
if(Willy.visit() < 2.) cont++;
}
std::cout << "cont = " << cont << std::endl;
std::vector<Location> loc;
Location a(0.1, 0.1);
Location b(0.5, 0.1);
Location c(0.5, 0.5);
loc.push_back(a);
loc.push_back(b);
loc.push_back(c);
std::vector<Salesman*> vett;
vett.push_back(new Salesman(start2, loc.begin(), loc.end()));
vett.push_back(new LazySalesman(0.1, loc.begin(), loc.end()));
vett.push_back(new LazySalesman(0.5, loc.begin(), loc.end()));
for(auto el : vett) {
std::cout << el->visit() << std::endl;
delete el;
}
}