I get a NxM sized matrix and I have to find the max value, the number of max values and the lines that contain it.
I tired using three for{for{}} loops, but it took too long. This method seems to work for small inputs, but when I try it with a 1000x1000 matrix, it finishes before it even takes all the input.
I realise this may be too much of a noob question, but I couldn't find anything else.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
for(int i=0; i<n; i++)
{
for(int p=0; p<m; p++)
{
cin >> vekt[p];
}
for(int j=0; j<m; j++)
{
if(vekt[j] == crnt)
{
lines[cnt] = i + 1;
cnt += 1;
}
if(vekt[j] > crnt)
{
crnt = vekt[j];
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
EDIT : not using vector or [n] was just easier... I simply saved it to a variable and used a bool:
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
bool inLine;
inLine = false;
for(int i=0; i<n; i++)
{
inLine = false;
for(int j=0; j<m; j++)
{
cin >> inp;
if(inp == crnt && inLine == false)
{
lines[cnt] = i + 1;
cnt += 1;
inLine = true;
}
if(inp > crnt)
{
crnt = inp;
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
This cut the time by enough so that I went under the limit.
int vekt[m]; is not standard C++, it is a variable length array (which some compilers allow as extension). Use std::vector instead.
That would also fix the bug you currently have: If cnt >= n (i.e. if you find more maxima than the matrix has lines), you will go out of bounds of lines and your program will most likely crash (although anything could happen), which is more likely to happen with larger matrices.
You can do this instead:
Declaration and initialization:
std::vector<int> linesWithMaxima;
When you find another value equal to the current maximum:
linesWithMaxima.push_back(i+1);
When you find a new maximum (larger than current):
linesWithMaxima.clear();
linesWithMaxima.push_back(i+1);
Note that this will list a line with multiple (identical) maxima multiple times. If you want to avoid duplicates, you can either check that you have not already added the current line (linesWithMaxima.back() != i+1) or use std::sort, std::unique and std::vector::erase.
Other than that your code looks fine. I would recommend naming the loop indices better (line instead of i etc.) and possibly merging the p and j loop because separating them seems to have no purpose. And if you want the most negative integer, use std::numeric_limits<int>::lowest().
Check this realization, without STL and vectors:
void input_matrix(int **&matrix, int &lines, int &columns)
{
int m = 0, n = 0;
cout << "input lines count:";
cin >> m;
cout << "input rows count:";
cin >> n;
matrix = new int *[m];
for(int i = 0;i < m;i++)
matrix[i] = new int[n];
cout << endl << "input matrix:" << endl;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
lines = m;
columns = n;
}
void print_matrix(int **&matrix, int &lines, int &columns)
{
for(int i = 0; i < lines; i++)
{
for(int j = 0; j < columns; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
int find_max(int **matrix, int lines, int columns, int &max_count)
{
int max = INT_MIN;
max_count = 0;
for(int i = 0; i < lines; i++)
for(int j = 0; j < columns; j++)
{
if(matrix[i][j] > max)
{
max = matrix[i][j];
max_count = 1;
}
else
if(matrix[i][j] == max)
++max_count;
}
return max;
}
int main()
{
int **matrix = nullptr;
int m=0, n=0, count=0;
input_matrix(matrix, n, m);
cout << endl;
print_matrix(matrix, n, m);
cout << endl;
int max = find_max(matrix, n, m, count);
cout << "max=" << max << " count=" << count << endl;
for(int i = 0; i < n; i++)
delete[]matrix[i];
delete []matrix;
}
As requested by mister Max Langhof I would also like to propose a more modern solution, based on the std::vector container, which does not need pointers and manual memory management. It's a simple class matrix:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
class matrix
{
private:
vector<vector<int>> m_data;
public:
matrix(int cols, int rows)
{
m_data.resize(cols);
for(auto &r : m_data)
r.resize(rows);
}
int max_element()
{
int max = INT_MIN;
for(auto &row: m_data)
{
auto maxinrow = *std::max_element(row.begin(), row.end());
if(maxinrow > max)
max = maxinrow;
}
return max;
}
int element_count(int elem)
{
int count = 0;
for(auto &row : m_data)
count += std::count_if(row.begin(), row.end(), [elem](int a){return a == elem;});
return count;
}
friend istream& operator>>(istream &os, matrix &matr);
friend ostream& operator<<(ostream &os, matrix &matr);
};
Input and output operators could be realized like this:
istream& operator>>(istream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cin >> matr.m_data[i][j];
cout << endl;
}
return os;
}
ostream& operator<<(ostream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cout << matr.m_data[i][j] << " ";
cout << endl;
}
return os;
}
And a sample of using of this matrix:
int main()
{
int m = 5, n = 4;
matrix matr(m, n);
cout << "input matrix:" << endl;
cin >> matr;
cout << endl << matr;
int max = matr.max_element();
cout << "max: " << max << " count:" << matr.element_count(max) << endl;
}
Checkout something like this
#include <iostream>
#include <set>
#include <vector>
int main() {
int rowsNo, columnsNo;
std::cin >> rowsNo >> columnsNo;
std::vector<int> matrix(rowsNo*columnsNo);
//Creating matrix
for(auto row = 0; row < rowsNo; ++row) {
for (auto column = 0; column < columnsNo; ++column)
std::cin >> matrix[row*columnsNo + column];
}
auto maxValue = -51;
//Finding positions of maximums
std::set<int> linesWithMaxValue;
for (auto position = 0; position < matrix.size(); ++position) {
if(matrix[position] == maxValue)
linesWithMaxValue.insert(position / columnsNo);
else if(matrix[position] > maxValue) {
linesWithMaxValue.clear();
maxValue = matrix[position];
linesWithMaxValue.insert(position / columnsNo);
}
}
//Print info
const auto numberOfMaxValues = linesWithMaxValue.size();
std::cout << "Number of maxiums: " << numberOfMaxValues << std::endl;
std::cout << "Lines that contains maximum:";
for (const auto& lineId : linesWithMaxValue)
std::cout << " " << lineId;
return 0;
}
Related
I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m, x;
int a[n][m];
cin>>n>>m;
for(int i; i<n ; i++)
{
for(int j; j<m ; j++)
{
cout<<"Enter the values";
cin>>x;
a[i][j] = x;
}
}
return 0;
}
here it gets error:
main.cpp|6|warning: 'm' is used uninitialized in this function [-Wuninitialized]|
main.cpp|6|warning: 'n' is used uninitialized in this function [-Wuninitialized]|
You can't declare the array unknown size. You must do it dynamically.
#include <iostream>
using namespace std;
int main()
{
int n = 0, m = 0;
//. Get the matrix's size
while (true)
{
cout << "Input the row count: "; cin >> n;
cout << "Input the column count: "; cin >> m;
if (n < 1 || m < 1)
{
cout << "Invalid values. Please retry." << endl;
continue;
}
break;
}
//. Allocate multi-dimensional array dynamically.
int ** mat = new int *[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[m];
}
//. Receive the elements.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << "Input the element of (" << i + 1 << "," << j + 1 << "): ";
cin >> mat[i][j];
}
}
//. Print matrix.
cout << endl << "Your matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << mat[i][j] << "\t";
}
cout << std::endl;
}
//. Free memories.
for (int i = 0; i < n; i++)
{
delete[] mat[i];
}
delete[] mat;
return 0;
}
If you like to use stl, it can be simple.
#include <iostream>
#include <vector>
using namespace std;
using ROW = vector<int>;
using MATRIX = vector<ROW>;
int main()
{
int n = 0, m = 0;
MATRIX mat;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
ROW row;
row.resize(m);
for (int j = 0; j < m; j++)
{
cin >> row[j];
}
mat.push_back(row);
}
for (auto & row : mat)
{
for (auto & iter : row)
{
cout << iter << "\t";
}
cout << endl;
}
return 0;
}
Some comments.
Please never use #include<bits/stdc++.h>. This is a none C++ compliant compiler extension
Please do not use using namespace std;. Always use fully qualified names.
For the above to statements you will find thousands of entries here on SO
In C++ you cannot use VLAs, Variable Length Array, like int a[n][m];. This is not part of the C++ language
You should not use C-Style arrays at all. Use std::array or, for your case std::vector.
Use meaningful variable names
Write comments
Always initialize all variables, before using them!!!
And, last but not least. You will not learn C++ on this nonesens "competition - programming" sites.
And one of many millions possible C++ solutions (advanced) could look like that:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Read the dimension of the 3d data
if (unsigned int numberOfRows{}, numberOfCoulmns{}; (std::cin >> numberOfRows >> numberOfCoulmns) and (numberOfRows > 0u) and (numberOfCoulmns > 0u)) {
// Define a vector with the requested size
std::vector<std::vector<int>> data(numberOfRows, std::vector<int>(numberOfCoulmns, 0));
// Read all data
std::for_each(data.begin(), data.end(), [&](std::vector<int>& col) mutable
{ auto it = col.begin(); std::copy_n(std::istream_iterator<int>(std::cin), numberOfCoulmns, it++); });
// Show debug output
std::for_each(data.begin(), data.end(), [](std::vector<int>& col)
{std::copy(col.begin(), col.end(), std::ostream_iterator<int>(std::cout, "\t")); std::cout << '\n'; });
}
else std::cerr << "\nError: Invalid input given\n\n";
return 0;
}
void Numbers()
{
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
cout << "Enter the first number: ";
cin >> N;
}
double Sum()
{
vector<double> arr(K);
arr.push_back(N);
for (int i=0; i < arr.size(); i++)
arr.at(i)=i;
cout << "Vector contains: ";
for (int i=0; i < arr.size(); i++)
cout << arr.at(i);
int main()
{
Numbers();
Sum();
return 0;
}
Write a program that generates sequence of K (K > 3) numbers as follows:
The members of the above sequence are obtained as follows:
the first element is N;
the second one is N + 1;
the third - N * 2.
In other words, we consistently add 1 to each element and put it to the end of the sequence, then multiply it by 2 and again, put the product to the end of the sequence. Choose and implement a suitable data structure that can be used to generate the above sequence of numbers.
The users should enter values for K and first element N.
This is my current code(in the code above). I don`t realy know where to go from here onward to be completely honest. Any suggestions on how to create the sequence from the condition above?
You can use this code to get what you want:
#include <iostream>
#include <vector>
using namespace std;
vector<double> createOutputArray (int K, int N)
{
vector<double> arr;
int tmp = N;
arr.push_back(tmp);
for(int i=1; i+2<=K; i+=2)
{
arr.push_back(++tmp);
arr.push_back(tmp * 2);
tmp *= 2;
}
if(K % 2 == 0)
arr.push_back(++tmp);
return arr;
}
int main()
{
int K;
double N;
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
cout << "Enter the first number: ";
cin >> N;
vector<double> output = createOutputArray(K, N);
for (int i=0; i < output.size(); i++)
{
cout << output.at(i);
if(i < output.size()-1)
cout << ",";
else
cout << endl;
}
return 0;
}
Here is one possibility, using a generator to produce the next element in the sequence.
class Seq
{
public:
Seq(int n) : n(n) {}
int operator*() const { return n; }
Seq operator++(int)
{
Seq old(n);
n = fns[fn](n);
fn = 1 - fn;
return old;
}
private:
int n;
int fn = 0;
std::function<int(int)> fns[2] = {[](int x) { return x + 1; },
[](int x) { return x * 2; }};
};
int main()
{
int N = 1;
int K = 20;
Seq seq(N);
for (int i = 0; i < K; i++)
{
std::cout << *seq++ << ' ';
}
std::cout << std::endl;
}
It gives the following error:
error C2872: 'count' : ambiguous symbol
Count variable has been declared as a global variable and the code compiles and runs in Sublime Text. Don't understand why Visual Studio is crying over it.
#include <iostream>
#include <fstream>
using namespace std;
int** am; // Adjacency matrix
int* ar, * ar2; // Arrays to work with
int n; // Number of nodes
int node1, node2, k; // For reading input from the console
int count;
bool checkReachability(int, int, int);
void fillArray(int);
void updateArray(int,int);
void freeMemory();
int main() {
ifstream in;
in.open("Input2.txt");
int a, b;
if(in.is_open()) {
in >> n;
// Allocate memory on the heap dynamically for the adjacency matrix:
am = new int*[n];
ar = new int[n];
ar2 = new int[n];
for (int i = 0; i < n; i++) {
am[i] = new int[n];
}
// Initialize the values of the adjacency matrix with 0s and the principle diagonal with 1s initially:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
am[i][j] = 1;
} else {
am[i][j] = 0;
}
}
}
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
cout << "The adjacency matrix input is as follows: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << am[i][j] << " ";
}
cout << endl << endl;
}
in.close();
} else {
cout << "\nError reading the input file\n\n";
}
char c;
do {
cout << "\nPlease enter the input (node1, node2, k): \n";
cin >> node1 >> node2 >> k;
fillArray(node1-1);
count = 0;
if(checkReachability(node1-1,node2-1,k)) {
cout << "\nReachable within " << k << " steps";
if (count < k) {
cout << " (actually " << count << ")";
}
cout << endl << endl;
} else {
cout << "\nNot reachable within " << k << " steps \n";
}
cout << "\nDo you want to continue? Y/N \n\n";
cin >> c;
} while (c == 'Y' || c == 'y');
freeMemory();
system("pause");
return 0;
}
bool checkReachability(int n1, int n2, int k) {
if (n1 == n2) return true;
count++;
if (count <= k) {
if (ar[n2] != 0) return true;
int x;
for (int i = 0; i < n; i++) {
if (ar[i] != 0 && i != n1) {
ar[i]++;
x = ar[i];
}
}
for(int i = 0; i < n; i++) {
ar2[i] = ar[i];
}
for(int i = 0; i < n; i++) {
if (ar2[i] == x) {
fillArray(i);
updateArray(x,i);
if (checkReachability(ar2[i], n2, k)) return true;
}
}
}
return false;
}
void fillArray(int x) {
// To fill the array with the adjacencies of a particular node
for(int i = 0; i < n; i++) {
ar[i] = am[x][i];
}
}
void updateArray(int x, int y) {
for(int i = 0; i < n; i++) {
if (ar[i] == 1 && i != y) {
ar[i] = x;
}
}
}
void freeMemory() {
// To free the dynamically allocated memory on the heap
for (int i = 0; i < n; i++) {
delete [] am[i];
}
delete [] ar;
delete [] ar2;
}
using namespace std is your problem.
Looks like the Microsoft implementation of either the iostream or fstream headers themselves include algorithm. This is causing the name clash with std::count().
So, as #Retiredninja suggested, if I choose to replace while(!in.eof()) with while(in >> a >> b) in:
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
Does the rest of the code in the while loop remain the same or does it mean, the input has already been read into a and b when the condition is checked in while(in >> a >> b)?
And become the following:
while(in >> a >> b) {
am[a-1][b-1] = 1;
}
or does it remain:
while(in >> a >> b) {
in >> a >> b;
am[a-1][b-1] = 1;
}
I'm studying C++ and I had the task to create array[n][m], to fill it with integer numbers, then
"Characteristic of matrix rows is called the sum of its positive even elements. You need to sort the rows of the matrix in accordance with the growth of characteristics."
It's my code
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int n, m;
cout << "n = ";
cin >> n;
cout << "m = ";
cin >> m;
int ** mas = new int * [n];
for (int i = 0; i < n; ++i)
{
mas[i] = new int[m];
}
cout << "Array:\n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
mas[i][j] = rand()%41-20;
cout << mas[i][j] << "\t";
}
cout << "\n";
}
double * characteristic = new double[n];
for (int i = 0; i < n; ++i)
{
characteristic[i] = 0;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if((j%2 == 0) && (mas[i][j] >= 0))
{
characteristic[i] += mas[i][j];
}
}
}
cout << "Characteristics:\n";
for (int i = 0; i < n; ++i)
{
cout << characteristic[i] << " ";
}
cout << "\n";
for (int i = 0; i < n - 1; ++i)
{
int min = i;
for (int j = i + 1; j < n; ++j)
{
if (characteristic[min] <= characteristic[j]) continue;
min = j;
}
if (min != i)
{
double temp = characteristic[i];
characteristic[i] = characteristic[min];
characteristic[min] = temp;
for (int k = 0; k < m; ++k)
{
int temp1 = mas[i][k];
mas[i][k] = mas[min][k];
mas[min][k] = temp1;
}
}
}
cout << "\nSorted characteristics:\n";
for (int i = 0; i < n; ++i)
{
cout << characteristic[i] << " ";
}
cout << "\n";
cout << "Sorted array:\n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cout << mas[i][j] << "\t";
}
cout << "\n";
}
for (int i = 0; i < n; ++i)
{
delete [] mas[i];
}
delete [] mas;
delete [] characteristic;
system("PAUSE");
return 0;
}
I created another one array for characteristics and sorted it and the first array at the same time, but it seems I used too difficult way to accomplish a given task. Maybe are there other ways?
Did you want to sort the matrix too, using the same ordering as the 'characteristic's?
Let's say you had C++ style code to calculate the characteristics:
std::vector<double> characteristic(n, 0.0);
std::transform(begin(mas), end(mas), begin(characteristic), sum_);
You could then sort them:
std::sort(begin(characteristic), end(characteristic));
Or you could, indeed sort the matrix immediately:
std::sort(begin(mas), end(mas), [&sum_](int_vec const& a, int_vec const& b)
{ return sum_(a)<sum_(b); });
Edit Fixed all versions to use the correct "characteristic sum" (kept the name though), thanks #Adam
Here's a full program that demonstrates this: See it Live on Coliru
#include <random>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
typedef std::vector<int> int_vec;
srand((unsigned)time(NULL));
int n, m;
cout << "n = ";
cin >> n;
cout << "m = ";
cin >> m;
std::vector<int_vec> mas(n, int_vec(m));
for (auto& v : mas)
std::for_each(begin(v), end(v), [](int& i) { i = rand()%41-20; });
cout << "Array:\n";
for (auto const& v : mas)
{
std::copy(begin(v), end(v), ostream_iterator<int>(cout, "\t"));
cout << "\n";
}
auto sum_ = [m](int_vec const& v) {
double vchar = 0;
for (auto j = 0; j < m; j+=2)
if(v[j] >= 0) vchar += v[j];
return vchar;
};
std::vector<double> characteristic(n, 0.0);
std::transform(begin(mas), end(mas), begin(characteristic), sum_);
cout << "Characteristics:\n";
std::copy(begin(characteristic), end(characteristic), ostream_iterator<double>(cout, " "));
cout << "\n";
std::sort(begin(characteristic), end(characteristic));
cout << "\nSorted characteristics:\n";
std::copy(begin(characteristic), end(characteristic), ostream_iterator<double>(cout, " "));
cout << "\n";
std::sort(begin(mas), end(mas), [&sum_](int_vec const& a, int_vec const& b) { return sum_(a)<sum_(b); });
cout << "Sorted Array:\n";
for (auto const& v : mas)
{
std::copy(begin(v), end(v), ostream_iterator<int>(cout, "\t"));
cout << "\n";
}
}
Sample output:
n = m = Array:
11 15 19 18
-20 -16 2 -11
8 2 19 8
Characteristics:
30 2 27
Sorted characteristics:
2 27 30
Sorted Array:
-20 -16 2 -11
8 2 19 8
11 15 19 18
#sehe gives you great advice, but I suspect a lot of that stuff won't make sense until you know more C++.
Here's a simple improvement to eliminate a slow loop:
When doing your row swaps swap the row pointers instead of copying every value that they point to. Replace this:
for (int k = 0; k < m; ++k)
{
int temp1 = mas[i][k];
mas[i][k] = mas[min][k];
mas[min][k] = temp1;
}
With:
int* temp1 = mas[i];
mas[i] = mas[min];
mas[min] = temp1;
If you can figure out how to use a built-in sort algorithm that would be another improvement on top of this, but even this small change will gain you a lot.
Since the sizes n,m are known in compile time, you can use the qsort function from the C library.
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Where is compar is a function you write, which should treat both its arguments as pointers to a row of the matrix. Then it can calculate the characteristic of both rows, and return -1, 0 or 1 depending on which row's characteristic is greater.
I am trying to create some test cases for my 'minimum dot product' problem. I want 10 test cases , each generating different set of values for both vector a and b.
The Problem is that even after using srand( time( NULL ) ) though a new input is generated every time I compile and run the code but that same input is used for all the 10 test cases.
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using std::vector;
void sort_asc(vector<int> &manav, int sizes)
{
int temp = 0;
for (int i = 0; i<sizes; i++)
{
for (int j = i + 1; j<sizes; j++)
{
if (manav[i] > manav[j])
{
temp = manav[i];
manav[i] = manav[j];
manav[j] = temp;
}
}
}
std::cout << "b in asc order : ";
for (int i = 0; i<sizes; i++)
{
std::cout << manav[i] << " ";
}
std::cout << std::endl;
}
void sort_desc(vector<int> &manav, int sizes)
{
int temp = 0;
for (int i = 0; i<sizes; i++)
{
for (int j = i + 1; j<sizes; j++)
{
if (manav[i] < manav[j])
{
temp = manav[i];
manav[i] = manav[j];
manav[j] = temp;
}
}
}
std::cout << "a in desc : ";
for (int i = 0; i<sizes; i++)
{
std::cout << manav[i] << " ";
}
std::cout << std::endl;
}
long long min_dot_product(vector<int> a, vector<int> b, int sizes) {
long long result = 0;
sort_desc(a, sizes);
sort_asc(b, sizes);
for (size_t i = 0; i < sizes; i++) {
result += a[i] * b[i];
}
return result;
}
int main() {
srand(time(NULL));
/*
std::cin >> n;
vector<int> a(n), b(n);
for (size_t i = 0; i < n; i++) {
std::cin >> a[i];
}
for (size_t i = 0; i < n; i++) {
std::cin >> b[i];
}
*/
//================================================================ TESTING =========================================================================
int z = 0;
int n = (rand() % 10) + 1; // generating the size of the vectors [1-10]
std::cout << "n = " << n << "\n";
vector<int> a;
vector<int> b;
while (z != 10) {
for (int i = 0; i < n; ++i)
{
int p = (rand() % 10) - 5;
a.push_back(p); // input values [-5,4] in 'a'
}
std::cout << "Unsorted Vector a = ";
for (int i = 0; i<n; i++)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < n; ++i)
{
int q = (rand() % 10) - 5;
b.push_back(q); // inputing values [-5,4] in 'b'
}
std::cout << "Unsorted Vector b = ";
for (int i = 0; i<n; i++)
{
std::cout << b[i] << " ";
}
std::cout << std::endl;
std::cout << "min_dot_product = " << min_dot_product(a, b, n) << std::endl;
z++;
}
return 0;
}
I somehow want to generate a different set of values for vector a and b for all of the 10 test cases every time I run the code.
I have tried srand(i) within the respective for loops before pushing the value in vectors but its not working for me, also reusing srand( time( NULL ) ) within the for loops is not gonna help either. Is there some other simple way I can achieve this?
The problem is you never clear out the vector on each iteration. Since you don't all of the new random numbers you generate are being added to the end of the vector and you ignore them since n never changes.
What you need to do is add
a.clear();
b.clear();
to the end of the while loop. This will clear out the vectors and then when you start the next iteration the new random numbers will get added into the part of the vector you use in your functions.
You could also set the vector the proper size and then use [] to access the elements. This way you would just overwrite the previous values and you would not have to call clear()
vector<int> a(n);
vector<int> b(n);
//...
for (int i = 0; i < n; ++i)
{
a[i] = (rand() % 10) - 5;
b[i] = (rand() % 10) - 5;
}
I put both assignments in the same for loop to save space. You can do this in two separate loops but it is not needed.