Hi everyone. I'm new to C++. I'm seeking for some advise here. I had some problem here. Given matrix (5x15) known as route as below. For each row, I need to select one number randomly and then swap with number next to it. So, the problem is, I need to do this process for 5 generations but the result I obtain for generation 2, 3, 4 and 5 are based on the previous solution.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
8 7 6 5 4 3 2 1 15 14 13 12 11 10 9
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
2 4 6 8 10 12 14 15 1 3 5 7 9 11 13
1 3 6 9 12 15 2 4 8 10 14 5 7 13 11
Generation 1
Random no: 4
After swap should be:
1 2 3 5 4 6 7 8 9 10 11 12 13 14 15
8 7 6 5 3 4 2 1 15 14 13 12 11 10 9
15 14 13 12 11 10 9 8 7 6 5 3 4 2 1
2 6 4 8 10 12 14 15 1 3 5 7 9 11 13
1 3 6 9 12 15 2 8 4 10 14 5 7 13 11
Generation 2
Random no: 8
1 2 3 4 5 6 7 9 8 10 11 12 13 14 15
7 8 6 5 4 3 2 1 15 14 13 12 11 10 9
15 14 13 12 11 10 9 7 8 6 5 4 3 2 1
2 4 6 10 8 12 14 15 1 3 5 7 9 11 13
1 3 6 9 12 15 2 4 10 8 14 5 7 13 11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
// Initialise random seed
srand(time(NULL));
vector<vector<int>> route;
ifstream route_data("route.txt");
for (string line; getline(route_data, line); )
{
route.push_back(vector<int>());
istringstream iss(line);
for (int n; iss >> n; )
route.back().push_back(n);
}
int generation = 5;
for (size_t i = 0; i < generation; i++)
{
cout << "Generation: " << i + 1 << "\n";
cout << "\n";
int rand_num = rand() % 15;
cout << "Random number = " << rand_num << "\n";
cout << "\n";
for (size_t i = 0; i < route.size(); i++)
{
// Iterator to store the position of searched element
vector<int>::iterator it, ik;
// Find position of rand_num
it = find(route[i].begin(), route[i].end(), rand_num);
if (it != route[i].end())
ik = it + 1;
// Swap it and ik
if (it != route[i].end() && ik != route[i].end())
{
iter_swap(it, ik);
}
for (size_t j = 0; j < route[i].size(); j++)
{
cout << route[i][j] << " ";
}
cout << "\n";
}
cout << "\n";
}
}
|