I want to generate different random numbers . I used srand and rand , but in my output some numbers are identical .
This is my output :
How to do with srand to generate different numbers ?
#include<iostream>
#include<time.h>
#include <windows.h>
int main(){
time_t t;
std::vector<int> myVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 40; i++){
int b = rand() % 100;
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
Sleep(50000);
}
One easy way is to add all numbers from 0-99 to a vector and shuffle it, then you can get as many (up to 100) non repeating random numbers as you require.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
int main(void) {
std::vector<int> numbers;
for(int i=0; i<100; i++) // add 0-99 to the vector
numbers.push_back(i);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(numbers.begin(), numbers.end(), std::default_random_engine(seed));
for(int i=0; i<40; i++) // print the first 40 randomly sorted numbers
std::cout << numbers[i] << std::endl;
}
You could use a set:
std::set<int> numbers;
while (numbers.size() < 40)
{
numbers.add(rand() % 100);
}
and then copy it into a vector if necessary.
srand number generator can give identical numbers.
You could implement a solution which deletes duplicates not adding them to the vector. For example:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> myVector;
srand((unsigned)time(NULL));
while(myVector.size() < 40)
{
int b = rand() % 100;
if ( !(std::find(myVector.begin(), myVector.end(), b) != myVector.end()))
{
myVector.push_back(b);
std::cout << myVector.at(myVector.size()-1) << std::endl;
}
}
Sleep(50000);
return 0;
}
An easy way of getting rid of duplicates is using std::unique in <algorithm>.
Here is an example of that in use:
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
int ran(int min, int max)
{
std::random_device r;
std::mt19937 gen(r());
std::uniform_int_distribution<> dis(min, max);
return dis(gen);
}
int main()
{
const int fill_size = 10;
const int min = 1; // min random number
const int max = 100; // max random number
std::vector<int> vec;
while (vec.size() != fill_size) {
vec.emplace_back(ran(min, max)); // create new random number
std::sort(begin(vec), end(vec)); // sort before call to unique
auto last = std::unique(begin(vec), end(vec));
vec.erase(last, end(vec)); // erase duplicates
}
std::random_shuffle(begin(vec), end(vec)); // mix up the sequence
for (const auto& i : vec) // and display elements
std::cout << i << " ";
}
As for me, the idea of using set is not so good, because the generating time of every new value increases. If you have enough memory it seems that usage of an array can be preferable.
In the next code, I don't use shuffle, instead, I use a random function just size times to choose one value. I add it to the destination vector, then in the source array, swap the value with the last element and decrease arr_size.
/*
* Return random unsigned int value using intrinsic
* */
unsigned getRandom() {
unsigned val;
_rdrand32_step(&val);
return val;
}
/*
* Return a vector<int> of uniq numbers in a range of [min ... max).
*
* #param min - min value.
* #param max - max value.
* #param size - amount of uniq numbers (size <= max-min).
* */
vector<int> getUniqNumbers(int min, int max, unsigned size) {
int arr_size = max - min;
int *a = new int[arr_size];
for (int i = 0; i < arr_size; i++) {
a[i] = min + i;
}
vector<int> numbers(size);
for (int i = 0; i < size; i++) {
unsigned u_rand = getRandom() % arr_size;
numbers[i] = a[u_rand];
a[u_rand] = a[--arr_size];
}
delete[] a;
return numbers;
}
You can easily achieve a unique set of random numbers writing:
#include<iostream>
#include<vector>
int main(){
std::vector<int> myVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 40; i++) {
int b = rand() % 100;
if(!std::find(std::begin(myvector),std::end(myvector),b)) {
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
}
}
This is a statistical (mathematical) issue. Random numbers may be identical to eachother. If you need unique numbers, you must check to see if they are used before. For example like this:
for (int i = 0; i < 40; i++){
int b = rand() % 100;
for (int j = 0; j < i; j++){
if(myVector[j]==b)i--;
else{
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
}
}
Related
I am trying to create a sequence of 4 different numbers and randomly generated from 0 to 100 but it must have number 86, here is what I did:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Loop to get 3 random numbers
for(int i = 0; i < 3; i++)
{
int random = rand() % 101;
// Print the random number
cout << random << endl;
}
cout << 86 << endl;
}
But I don't want to put 86 at the end, are there any ways to place it at any random position in the sequence ? Thank you
My approach using modern C++
#include <algorithm>
#include <iostream>
#include <array>
#include <random>
namespace {
std::default_random_engine generator(std::random_device{}());
int random(int min, int max) {
return std::uniform_int_distribution<int>{min, max}(generator);
}
}
int main() {
std::array<int, 4> elements = {86};
for (int i = 1; i < elements.size(); ++i) {
elements[i] = random(0, 100);
}
std::shuffle(elements.begin(), elements.end(), generator);
for (int nbr : elements) {
std::cout << nbr << "\n";
}
return 0;
}
You can do exactly as you said - place it in a random position. First, you store the four numbers to be generated in an array; then, you decide which position is 86; then, you fill the rest and print it.
int main()
{
srand((unsigned) time(NULL));
int nums[4];
int loc86 = rand() % 4;
for(int i = 0; i < 4; i++)
{
nums[i] = i != loc86 ? rand() % 101 : 86;
}
for(int i = 0; i < 4; i++)
{
// Print the random number
cout << num[i] << endl;
}
}
A bit offtopic, but if you really care about precision of the random number generation (and that it approaches uniform random distribution well enough), you might use pragmatic c++ random number generators as described here.
Two approaches
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Take a random position
const int j = rand() % 4;
// Loop to get 3 random numbers
for(int i = 0; i < 4; i++)
{
if (i == j)
cout << 86 << endl;
else
cout << rand() % 101 << end;
}
}
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Fill and shuffle the array
int r[4] = {86, rand() % 101, rand() % 101, rand() % 101};
std::shuffle(std::begin(r), std::end(r));
for(int i = 0; i < 4; i++)
cout << r[i] << end;
}
Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]
C++ program for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to find the missing elements
void printMissingElements(int arr[], int N)
{
// Initialize diff
int diff = arr[0] - 0;
for (int i = 0; i < N; i++) {
// Check if diff and arr[i]-i
// both are equal or not
if (arr[i] - i != diff) {
// Loop for consecutive
// missing elements
while (diff < arr[i] - i) {
cout << i + diff << " ";
diff++;
}
}
}
}
Driver Code
int main()
{
// Given array arr[]
int arr[] = { 5,2,6 };
int N = sizeof(arr) / sizeof(int);
// Function Call
printMissingElements(arr, N);
return 0;
}
How to solve this question for the given input?
First of all "plzz" is not an English world. Second, the question is already there, no need to keep writing in comments "if anyone knows try to help me".
Then learn standard headers: Why should I not #include <bits/stdc++.h>?
Then learn Why is "using namespace std;" considered bad practice?
Then read the text of the problem: "Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]"
You need to "return the numbers from 1 to 10 which are missing."
I suggest that you really use C++ and get std::vector into your toolbox. Then you can leverage algorithms and std::find is ready for you.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
std::vector<int> missingElements(const std::vector<int> v)
{
std::vector<int> missing;
for (int i = 1; i <= 10; ++i) {
if (find(v.begin(), v.end(), i) == v.end()) {
missing.push_back(i);
}
}
return missing;
}
int main()
{
std::vector<int> arr = { 5, 2, 6 };
std::vector<int> m = missingElements(arr);
copy(m.begin(), m.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
return 0;
}
If you want to do something with lower computational complexity you can have an already filled vector and then mark for removal the elements found. Then it's a good chance to learn the erase–remove idiom:
std::vector<int> missingElements(const std::vector<int> v)
{
std::vector<int> m = { -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (const auto& x: v) {
m[x] = -1;
}
m.erase(remove(m.begin(), m.end(), -1), m.end());
return m;
}
By this approach we are using space to reduce execution time. Here the time complexity is O(N) where N is the no of elements given in the array and space complexity is O(1) i.e 10' .
#include<iostream>
void printMissingElements(int arr[], int n){
// Using 1D dp to solve this
int dp[11] = {0};
for(int i = 0; i < n; i++){
dp[arr[i]] = 1;
}
// Traverse through dp list and check for
// non set indexes
for(int i = 1; i <= 10; i++){
if (dp[i] != 1) std::cout << i << " ";
}
}
int main() {
int arr[] = {5,2,6};
int n = sizeof(arr) / sizeof(int);
printMissingElements(arr, n);
}
void printMissingElements(int arr[], int n,int low, int high)
{
bool range[high - low + 1] = { false };
for (int i = 0; i < n; i++) {
if (low <= arr[i] && arr[i] <= high)
range[arr[i] - low] = true;
}
for (int x = 0; x <= high - low; x++) {
if (range[x] == false)
std:: cout << low + x << " ";
}
}
int main()
{
int arr[] = { 5,2,6,6,6,6,8,10 };
int n = sizeof(arr) / sizeof(arr[0]);
int low = 1, high = 10;
printMissingElements(arr, n, low, high);
return 0;
}
I think this will work:
vector<int> missingnumbers(vector<int> A, int N)
{ vector<int> v;
for(int i=1;i<=10;i++)
v.push_back(i);
sort(A.begin(),A.end());
int j=0;
while(j<v.size()) {
if(binary_search(A.begin(),A.end(),v[j]))
v.erase(v.begin()+j);
else
j++;
}
return v;
}
I have a large array of numbers that range from 1-5. I need to get the total of each number in the array and and place it into another array, with the total of number of 1s in the first position of the array, total number of 2s in the second position, etc.
So if I had arr1[10] = {1,4,3,1,2,4,5,4,1,3}, I would want to get to arr2[5] = {3,1,2,3,1}.
However, with my current code, I get
1,0,0,1,0
Here is my code below:
n = 10
arr1[n] = {1,4,3,1,2,4,5,4,1,3}
arr2[5] = {0,0,0,0,0}
for (int i = 0; i < n; i++)
{
int rate = arr1[i];
if (arr2[i] == 0)
{
int count = 0;
if (rate == 1)
{
count += 1;
arr2[i] = count;
}
cout << count << endl;
}
}
Simply loop over the numbers in arr1 and increment the appropriate counter in arr2. Be aware that C arrays start at index 0 ;)
Only print the counts at the very end, once everything is tallied.
If you're allowed to use C++:
#include <vector>
#include <map>
#include <iostream>
using namespace std;
int main(void)
{
// Do count sort
// Init vector
vector<unsigned char> a = {1,5,3,4,2,2,4,5,1,1};
map<unsigned char, size_t> a_map;
// Populate map
for (size_t i = 0; i < a.size(); i++)
a_map[a[i]]++;
vector<unsigned char> b;
// Rebuild vector from map
for (map<unsigned char, size_t>::const_iterator ci = a_map.begin(); ci != a_map.end(); ci++)
{
for (size_t i = 0; i < ci->second; i++)
b.push_back(ci->first);
}
// Print sorted vector
for (size_t i = 0; i < b.size(); i++)
cout << static_cast<int>(b[i]) << endl;
return 0;
}
So I am trying to generate 10,000 random numbers from 1-100, but it is only generating up to 99 numbers because when I display it I can only see from 1-99, unless it is my code for finding it. What is happening in my code is i am trying to find how many times the number is generated. Basically a frequency/histogram.
EDIT:I am generating 100, but its not displaying, i get a error
Here is my code:
vector<int> vint;
for (int i = 0; i < 10000; i++)
{
int x = (rand() % 100) + 1;
vint.push_back(x);
}
frequency(vint);
void frequency (vector<int> v1)
{
int counter = 1;
int max = 0;
int mode = v1[0];
int numbercheck = 0;
for (int pass = 0; pass < 10000-1 ; pass++)
{
if (v1[pass] == v1[pass + 1])
{
counter++;
numbercheck++;
}
else
{
cout << v1[pass] << ": " << counter << "..................." << endl;
counter = 1;
}
}
If you are using a c++11 compatible compiler then avoid using rand() and use the Mersenne-Twister engine instead for higher quality random sequences. Here is a code snippet example:
#include <random>
int main(void) {
std::random_device rd; // for random seed
std::seed_seq seed{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
std::mt19937 eng(seed);
const int min = 1;
const int max = 100;
// used to generate ints in interval [min,max] (inclusive)
std::uniform_int_distribution<int> dist(min,max);
int randomInt = dist(engine); // generate random int using dist and mtengine
return 0;
}
See this (entertaining) video for some reasons on why rand() is bad:
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
You should accept ArchBishop's answer. Here is a simpler program for you.
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
vector<int> vint;
for(int i=0; i<10000; ++i)
{
vint.push_back(rand()%100 + 1);
}
for(const auto&e: vint)
cout << e << endl;
return 0;
}
It generated 100 for me but might not generate for you.
I am writing a counting sort function and when I run it, a window pops up saying "filename.exe has stopped working". After debugging it looks like it is getting stuck in the second for loop. What really confuses me, is if I set maxInt to any number greater than 130000 it works, but if its 130000 or lower than I get that error message. The file I'm using to sort only has about 20 numbers.
#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
std::string file = "";
std::vector<int> numbers;
void CountingSort(vector<int> &numbers);
int main()
{
std::cout << "Which file would you like to sort?\n";
std::cin >> file;
std::ifstream in(file.c_str());
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
CountingSort(numbers);
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
return 0;
}
struct CalcMaxInt
{
int maxInt;
CalcMaxInt () : maxInt(0) {}
void operator () (int i) { if (i > maxInt) maxInt = i; }
};
void CountingSort(vector<int>& numbers)
{
CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
//int maxInt = cmi.maxInt + 1;
int maxInt = 130001;
vector <int> temp1(maxInt);
vector <int> temp2(maxInt);
for (int i = 0; i < numbers.size(); i++)
{
temp2[numbers[i]] = temp2[numbers[i]] + 1;
}
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp1[temp2[numbers[i]] - 1] = numbers[i];
temp2[numbers[i]] = temp2[numbers[i]] -1;
}
for (int i =0;i<numbers.size();i++)
{
numbers[i]=temp1[i];
}
return;
}
You are trying to access an element out of proper range.
temp2 has range [0...maxInt-1] but the following code uses temp2[maxInt] which is out of range.
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
You'll have to fix temp2 to have maxInt+1 elements or i < maxInt to not to see the error.
Isn't the whole point of you doing this:
CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
To get the max element?
I'd change your code to the following.
void CountingSort(vector<int>& numbers)
{
CalcMaxInt cmi;
std::for_each(numbers.begin(), numbers.end(), cmi);
int maxInt = cmi.maxInt;
vector <int> temp1(maxInt);
vector <int> temp2(maxInt);
// then the rest the same starting with the for loops
// but with the fix that #kcm1700 mentioned to the for loop
}
Shouldn't temp1 be dimensioned numbers.size()+1?