I'm playing around with rand() and srand() functions and I was trying to make a counter for how many 1's I could get in a row with a 50/50 generator, yet it seems that it caps out at 15 numbers in a row.
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int MostInARow = 0, CurrentInARow;
bool randomised;
srand((int)time(NULL));
for (long int i = 0; i < 100000000; i++) {
CurrentInARow = 0;
randomised = rand() % 2;
while (randomised) {
randomised = rand() % 2;
CurrentInARow++;
}
if (CurrentInARow > MostInARow) {
system("CLS");
MostInARow = CurrentInARow;
cout << MostInARow;
}
}
return 0;
}
I'd love to learn why this happens.
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;
}
I want to make a method that generates an array with random values between 0 and 6 in it without repeating those values.
This is what I've got:
void randomArray(){
randNum = rand() % 6;
code[0] = randNum
for (int i = 1; i < 4; i++){
randNum = rand() % 6;
code[i] = randNum;
while (code[i] == code[i - 1]){
randNum = rand() % 6;
code[i] = randNum;
}
}
}
But I'm getting repeated values on the random-generated array.
PD: I also need to use a similar method to make an array of enum's.
You could do something like this:
int randomFromSet(std::vector<int>&_set)
{
int randIndex = rand() % _set.size();
int num = _set[randIndex];
_set.erase(_set.begin() + randIndex);
return num;
}
This chooses a random int from a provided set of numbers, and removes that choice from the set so that it can't be picked again.
Used like so:
std::vector<int> mySet {0,1,2,3,4,5,6};
std::cout<<randomFromSet(mySet)<<'\n;
#include <random>
#include <vector>
#include <numeric>
#include <iostream>
using std::cout;
using std::endl;
int main() {
const int sz = 7;
std::vector<int> nums(sz);
std::iota(std::begin(nums), std::end(nums), 0);
std::default_random_engine re;
int i = 8;
while(--i > 0) {
auto my_set{ nums };
std::shuffle(my_set.begin(), my_set.end(), re);
for (auto x : my_set) {
cout << x << " ";
}
cout << endl;
}
}
Im new to c++ , can I add my answer too?
its c-style c++ sorry for that.but its easy to code and to understand at the same time.
#include <iostream> //std::cout
#include <ctime> //time() function
#include <cstdlib> //rand() and srand() functions
void rand_gen(unsigned int arr[],unsigned int sizeofarray)
{
srand((unsigned int)time(0);
for (unsigned int c = sizeofarray ; c > 0 ; c--)
{
unsigned int r = rand()%sizeofarray;
if (arr[r] != 404)
{
std::cout<<"Try No."<<(sizeofarray+1)-c<<" : "<<arr[r]<<"\n";
arr[r] = 404;
} else { c++; }
}
}
int main()
{
unsigned int n[7]={0,1,2,3,4,5,6};
rand_gen(n,7);
std::cin.get();
return 0;
}
I seem to be having an issue that I've been stuck on for hours. I run the program, and it just hangs after asking for the user input. My computer also begins to slow down unless I terminate the program. I have no idea what the problem is. I have tried commenting out code to see where the issue may be coming from. I put a cout statement after asking for the input, and even that does not display.
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
#include <cstdlib>
#include <array>
#include "problem2.h"
using namespace std;
int binarySearch(int array[], int input);
void selectSort(int arr[], int n);
int problem2() {
srand(time(0)); // generate seed based on current system time
int rand[20];
int result;
int input = 1;
cout << "Enter a number to search for: ";
cin >> input;
cout << "testset ";
for (int z = 0; z < 19; z++) {
rand[z] = random() % 70;
cout << rand[15];
}
selectSort(rand, 20);
for (int t = 0; t < 20; t++) {
//cout << random1D[z];
}
result = binarySearch(rand, input);
//cout << result;
return 0;
}
int binarySearch(int arr[], int a) {
int high = 19;
int middle = 19/2;
int low = 0;
while (arr[middle] != a && low<= high) {
if (arr[middle] > a) {
high = middle - 1;
} else {
low = middle - 1;
}
if (low > high) {
}
}
return middle;
}
void selectSort(int arr[], int n) {
int min, temp;
for (int i = 0; i < n-1; i++) {
min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min])
min = j;
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
You have several loops, but all of them except for one have explicit termination. The for loops all end after a specific number of iterations, but your while loop is less certain. Your low is likely never going to be greater than your high, so the loop just keeps going.
Consider changing to low = middle + 1 or altering your logic to more likely ensure that low will eventually overtake high. Or, change the condition the while loop checks.
I need to generate random non repeating number array in C++, in this part of code I generate random numbers using, srand function, but some of the numbers are repeating. The main task is to generate random numbers for lottery ticket, so I need to generate numbers until golden number which is marked as int golden.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int golden = 31;
int i = 0;
int array[35];
srand((unsigned)time(0));
while(i != golden){
array[i] = (rand()%75)+1;
cout << array[i] << endl;
i++;
}
}
One strategy is to populate an array with numbers from 1 to 75, and then use std::random_shuffle() on it. You can then read the numbers from the array until you hit the golden number.
I had a similar task and used two functions to solve the problem of repeating numbers.
#include <iostream>
#include <ctime>
using namespace std;
void generateRandom(int array[], int length);
bool findVal(int array[], int size, int value);
int main() {
int arraySize = 10;
int array[arraySize];
generateRandom(array, arraySize);
for (auto i : array) {
cout << i << " ";
}
return 0;
}
void generateRandom(int array[], int length) {
srand((int) time(nullptr));
int temp;
for (int i = 0; i < length; ++i) {
temp = rand() % 20 + 1;
if (findVal(array, i, temp)) {
i--;
continue;
} else {
array[i] = temp;
}
}
}
bool findVal(int *array, int size, int value) {
for (int i = 0; i < size; ++i) {
if (array[i] == value) {
return true;
}
}
return false;
}
Within the generateRandom function, you can switch the 20 and 1 used in the for loop with your preferred upper and lower limits respectively.
Please read the task first: http://codeabbey.com/index/task_view/neumanns-random-generator
I have to keep track of the number of iterations, but I get very strange results. In the example after the task we have the numbers 0001 and 4100 and they should come to loop after 2 and 4 iterations. But my results are 1, 4 or if I change the place of the counter 2 or 5 but never 2 and 4. Here is my code:
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
int setvalue = 1; // use to exit the loop if setvalue == 0;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
while(setvalue == 1)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
setvalue = 0;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
Going in and out of a string the way you have is really very ugly and extremely expensive computationally.
Use
(value % 1000000) / 100;
instead to extract the middle four digits. This works by (1) taking the modulus to remove the leading two digits then (2) removing the last two with integer division.
As it's so much simpler, I suspect that will fix your bugs too.
Here is the correct code, thank you for all your help.
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
results_vec.push_back(value);
while(true)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
break;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}