Hi anyone, I'm new to C++ programming. I got a task to reverse the numbers in a certain range. I don't have idea how to do it. Hoping for help from anyone. Thank you.
input file:
44 83 30 29 61 88 93 91 90 59 58 99 79 64 43
8 50 75 87 82 80 69 14 65 28 42 41 74 5 57
100 84 17 51 72 68 85 78 47 45 15 52 8 50 75
8 50 75 87 82 80 69 14 65 28 42 41 74 5 57
65 87 82 80 69 14 75 8 50 28 42 41 74 5 57
85 78 47 45 68 15 52 8 50 75 87 82 80 69 14
96 97 11 27 25 24 63 26 13 40 81 10 73 31 60
57 5 74 41 42 28 50 8 75 87 82 80 69 14 65
8 50 75 87 82 80 69 14 65 28 42 41 74 5 57
14 87 82 80 69 65 75 8 50 28 42 41 74 5 57
I need to reverse the numbers from (i1 + 2) to (i2 - 1) for each row.
i1 and i2 is the random value.
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
//declare functions
void input();
void randomSwapReverse();
//declare variables & files
const int pop_size = 10;
const int column_initialR = 15;
vector< vector <int>> initial_route (pop_size, vector <int> (column_initialR,0));
int i, j;
void main()
{
input();
randomSwapReverse();
}
void input()
{
//open input files
ifstream inpInitialRoute("Initial route 15.txt");
//assign initial routes into array
for ( i = 0; i < initial_route.size(); i++ )
{
for ( j = 0; j < column_initialR; j++)
{
inpInitialRoute >> initial_route[i][j];
}
}
//close input files
inpInitialRoute.close();
}
void randomSwapReverse()
{
srand(time(NULL));
for (int i = 0 ; i < pop_size; i++)
{
for (int j = 0; j < column_initialR; j++)
cout << setw(3) << initial_route[i][j] << ' ';
cout << endl;
}
cout << endl;
for (int i = 0; i < pop_size; i++)
{
// Generate two different random value from col to col + 14, inclusive.
int i1, i2;
do
{
i1 = rand() % 15;
i2 = rand() % 15;
}
while (i1 == i2);
// Ensure i1 is less than i2; if not, swap them.
if (i1 > i2)
{
int temp = i1;
i1 = i2;
i2 = temp;
}
cout << "For row " << i << ", positions "
<< i1 << " and " << i2 << " were chosen.\n";
//Swap next value at position i1 with value at position i2.
swap(initial_route[i][i1 + 1], initial_route[i][i2]);
//Reverse values from position (i1 + 2) to (i2 - 1).
reverse(initial_route[i][i1 + 2], initial_route[i][i2 - 1]);
}
cout << endl;
for (int i = 0 ; i < pop_size; i++)
{
for (int j = 0; j < column_initialR; j++)
cout << setw(3) << initial_route[i][j] << ' ';
cout << endl;
}
cout << endl;
system("pause");
}
|
Thank for your help.