Samchon Framework for CPP  1.0.0
TSPRequest.hpp
1 #pragma once
2 
3 #include <iostream>
4 #include <samchon/examples/interaction/base/MasterBase.hpp>
5 
6 #include <samchon/examples/tsp/Travel.hpp>
7 #include <samchon/library/FactorialGenerator.hpp>
8 
9 namespace samchon
10 {
11 namespace examples
12 {
13 namespace interaction
14 {
15  class TSPRequest
16  {
17  private:
18  base::MasterBase *master;
19 
20  std::shared_ptr<tsp::Travel> best_travel;
21  size_t requested_size;
22  size_t completed_count;
23 
24  public:
25  TSPRequest(base::MasterBase *master)
26  {
27  this->master = master;
28  };
29  void init(size_t size)
30  {
31  best_travel = nullptr;
32  this->completed_count = 0;
33  this->requested_size = size;
34  };
35 
36  void optimize(std::shared_ptr<library::XML> xml)
37  {
38  std::shared_ptr<tsp::Travel> travel(new tsp::Travel());
39  travel->construct(xml);
40 
41  auto invoke = std::make_shared<protocol::Invoke>("optimizeTSP", travel->toXML());
42  size_t size = library::FactorialGenerator(travel->size()).size();
43 
44  std::cout << "Start Packer optimization: #" << size << std::endl;
45  init(size);
46  };
47  void replyOptimization(std::shared_ptr<library::XML> xml)
48  {
49  std::shared_ptr<tsp::Travel> travel(new tsp::Travel());
50  travel->construct(xml);
51 
52  std::cout << "A slave has finished his optimization: " << travel->calcDistance() << " km" << std::endl;
53 
54  // IF CURRENT TRAVEL IS SHORTER, MAKE IT THE BEST
55  if (best_travel == nullptr || best_travel->calcDistance() == 0 ||
56  travel->calcDistance() < best_travel->calcDistance())
57  {
58  std::cout << "The slave renewed the best solution" << std::endl;
59  best_travel = travel;
60  }
61 
62  // IF ALL TASKS ARE DONE, REPORT TO THE CHIEF
63  if (++completed_count == requested_size)
64  master->getParent()->sendData
65  (
66  std::make_shared<protocol::Invoke>("replyTSPOptimization", best_travel->toXML())
67  );
68  };
69  };
70 };
71 };
72 };