0
Fill random number into array with descending order
I’ve been struggling about how to fill random number into an array with descending order which means can not fill in array then sort it
7 Respostas
+ 6
A simple example by taking advantage of STL's facilities
#include <iostream>
#include <random>
#include <ctime>
#include <limits>
#include <vector>
#include <algorithm>
using namespace std;
bool sort_method(int a, int b) { return a > b; } // Comparisson function for Descending order (a < b for ascending one)
int main() {
size_t number_of_rands = 10;
// define a container to hold 10 random integer
vector<int> array(number_of_rands);
// prepare random generator engine
mt19937 rand_engine(static_cast<size_t>(time(nullptr)));
// range[0, 32767]
uniform_int_distribution<> range(0, numeric_limits<short>::max());
// populating the array with 10 random number specified in distributed range then printing the unsorted values
cout << "Before sort: ";
for (auto &i : array) {
i = range(rand_engine);
cout << i << " ";
}
cout << endl;
// Sorting...
sort(array.begin(), array.end(), sort_method);
// Printing out the sorted array
cout << "After sort: ";
for (const auto &i : array) {
cout << i << " ";
}
}
Random output:
Before sort: 201 8562 2151 18085 16409 20886 10550 13234 31215 18669
After sort: 31215 20886 18669 18085 16409 13234 10550 8562 2151 201
_____
https://en.cppreference.com/w/cpp/types/numeric_limits
https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
https://en.cppreference.com/w/cpp/algorithm/sort
http://www.cplusplus.com/articles/NhA0RXSz/
+ 3
Jimmy Chen When you say storing values with a specific order, you are literally say that do 3 things on-the-fly without storing it somewhere first:
1. generate random numbers
2. compare newly generated number with the previous ones
3. position each new number in the correct place in the list
I'd say at best you can implement a rudimentary solution by not following the A, B, and C of the C++ programming and rewriting the book.
+ 2
C++ Soldier (Babak) nice one ! You could use for_each and generate instead of for loops to show more example of stl
+ 1
Like this?
for_each (array.begin(), array.end(), [&range, &rand_engine](int i) {
i = range(rand_engine);
cout << i << " ";
});
I think it's a bit hard to read! 8D
+ 1
You can replace "&range, &rand_engine" by "&" for simplicity, but yes for_each is harder to use than for, but this for syntax was not available before C++11
+ 1
Yup! 8)
0
but the way you did is fill in array then sort it