Minimum calls to rand() C - c

Edit:
Sorry for the inconvinience that made because of my undetailed question.
So, i have an array of numbers (int) with 1000 cells (index 0-999)
and I need to fill all the cells of the array with unique random numbers by calling the rand() function in C, but i have to do it with only 1000 calls to the fuction.. (Every number that generated is inserted to the array), there cant be duplicated numbers in the array.
Any ideas how I can do it?
Note:
Here is a sample code to fill the array without limiting the number of calls to rand.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DO_RAND rand()%1000
#define ARR_SIZE 1000
int main()
{
int i,callToRand=0,j;
int array[ARR_SIZE];
srand(time(NULL));
for(i=0;i<ARR_SIZE;i++) //Runs on the whole array
{
array[i]=DO_RAND; //inserting random number to the array
callToRand++; //increasing the number of calls to rand() function
for(j=0;j<i;j++) //running on the array till the current cell
{
if(array[j]==array[i])
//checking if the number has already in the array.
{
array[i]=DO_RAND;
callToRand++;
j=-1; //staring the checker loop again
}
}
}
printf("The number of calls to the function rand() were: %d\n",callToRand);
system("PAUSE");
return (0);
}

Having finally stated that you want an array of unique numbers within the range of the array size, try this. Note that the numbers are not randomised - they are defined - the sequence is.
Your posted attempt was very inefficient, using two nested loops. This uses one loop to initialise the array and another to randomise the sequence. No need to count the calls to rand() which are obviously ARR_SIZE.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARR_SIZE 100 //1000
int main()
{
int i, j, temp;
int array[ARR_SIZE];
srand((unsigned)time(NULL));
for(i=0; i<ARR_SIZE; i++) // set up unique array
array[i] = i;
for(i=0; i<ARR_SIZE; i++) { // randomize the sequence
j = rand() % ARR_SIZE; // pick another (or same) index
temp = array[i]; // and swap the values
array[i] = array[j];
array[j] = temp;
}
for(i=0; i<ARR_SIZE; i++) // show results
printf ("%5d", array[i]);
printf ("\n");
return (0);
}

Related

How can I use the rand() function to generate a different number that hasn't been generated before?

// What I mean by this is shown by my example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int i;
int a;
for (a = 0;a <10;a ++) {
i = (rand()%10)+1; // generates a number from 1-10
printf("%d\n", i);
}
// I would like for the loop to generate a number that gives a number that was not generated before. For example, an output such as:
1,3,6,2,8,9,4,10,5,7
instead of:
3,9,10,3,7,9,2,7,10,1
In other words, I would like no copies.
You obviously don't just want no copies, but you want every number in a given set exactly once. This is, as commented by Robert, similar to shuffling a deck of cards. You don't have "decks" in C, but you can model one as an array:
int deck[] = {1,1,1,1,1,1,1,1,1,1};
This should represent 10 different "cards" (identified by their index in the array), each available one time. Now, just write code that "draws" cards:
int i = 0; // starting point for searching for the next card to draw
for (int n = 10; n > 0; --n) // how many cards are left
{
int skip = rand() % n; // randomly skip 0 .. n cards
while (1)
{
if (deck[i]) // card still available?
{
if (!skip) break; // none more to skip -> done
--skip; // else one less to skip
}
if (++i > 9) i = 0; // advance index, wrapping around to 0
}
deck[i] = 0; // draw the card
printf("%d\n", i+1); // and print it out
}
of course, seed the PRNG (e.g. srand(time(0))) first, so you don't get the same sequence every time.
The idea shown in the question is to print numbers within a range, without repetition. Here is one way to do that, by putting each value into an array and swapping its elements around.
A variation could be that you don't want to use all the possible numbers, in that case just change PICKED.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRLEN 10
#define PICKED 10
int main(void) {
int array[ARRLEN];
srand((unsigned)time(NULL)); // seed the PRNG
for(int i = 0; i < ARRLEN; i++) { // generate the numbers
array[i] = i + 1;
}
for(int i = 0; i < ARRLEN; i++) { // shuffle the array
int index = rand() % ARRLEN;
int temp = array[i];
array[i] = array[index]; // by randomly swapping
array[index] = temp;
}
for(int i = 0; i < PICKED; i++) { // output the numbers
printf("%d ", array[i]);
}
printf("\n");
}
Program output:
9 8 4 5 1 10 7 3 6 2
The library's PRNG is not very random, but for many cases that is not important. If it is, better algorithms are available.

C Array of Random Numbers Storage

Hi I want to know is there a way to store randnumber without prompting user for input. In this example we want user to store 16 randnumbers in array storerand without prompting the user for randnums for example:
#include<stdio.h>
#include<stdlib.h>
void main() {
int randnum;
int i=0;
int storerand[16]; // storing randnumbers
randnum=rand();
while(i <16){
storerand[i]=randnum; // why is this not storing 16 rand number how can i store 16 randnumbers
i++;
}
return 0;
An easy way to generate random numbers in C is to use the rand() function which comes with <stdlib.h>. Note that if you do not seed with the time library, you will receive the same random numbers every time you run your program.
#include <stdlib.h>
#include <time.h>
int main (void) {
//Uses system time to seed a proper random number.
srand(time(NULL));
//rand() generates a random integer
int a = rand();
//Use mod to restrict range:
int b = rand()%5; //random integer from 0-4
return 0;
}
You also need to make sure to increment your index i within your while loop.
while(i < 16) {
storerand[i] = rand();
i++;
}
You initialise randnum with a random value here:
randnum=rand();
And then you run your loop to put its value into each slot of your array. That means you're putting the same value into each slot.
while(i <16){
storerand[i]=randnum;
i++;
}
The solution is to call rand() each time around the loop:
for( i = 0; i < 16; i++ ) {
storerand[i] = rand();
}

how to print 5 unique strings from array of 10 strings

I am writing a code which will print 5 unique and random strings from an array of 10 strings. But my code doesn't print it uniquely, there are always some repetitions.
Here is my code, can anyone suggest how to make it print unique?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main(void){
char arr[10][10]={"abc","def","ghi","klm","nop","qrs","tuv","wxy","zab","cde"};
int i=0,j=0;
srand(time(0));
for(i=0;i<5;i++){
j=rand()%10;
printf("%d\n",j);
}
}
Just remember idices that have already been printed out:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
char arr[10][10] = {"abc","def","ghi","klm","nop","qrs","tuv","wxy","zab","cde"};
int i = 0, j = 0;
int done[10] = { 0 };
srand(time(0));
for (i = 0; i < 5; ++i)
{
do
{
j = rand()%10;
}
while (done[j] == 1);
done[j] = 1;
printf("%s\n", arr[j]);
}
return 0;
}
Your rand() function may evaluate to the same string index multiple times. There are different ways to resolve that. Most of them will be a take off on bit vector approach. You can create a Boolean array and initialize it to false. Whenever a number is printed, you can change the element in the Boolean array for that index to true. If an element is selected, you can check in the Boolean array if it has already been printed. If yes, you can regenerate the random number, or move to the next unprinted element, making sure that the corresponding Boolean entry is changed to true when you print that element.
Your random function gives the repetition, e.g. your dice throw '3' two time out of 4 throws.
What you could do to make it simple, create an array [0..9],
and let the random function swap a[i] with a[j].
Then you get a random permutation. Take the first 5 elements of the permutated array.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <time.h>
int main(){
char arr[10][10]={"abc","def","ghi","klm","nop","qrs","tuv","wxy","zab","cde"};
int found[10] = { 0 };
int i = 0,j = 0;
srand(time(NULL));
for(i = 0; i < 5; i++){
j = rand() % 10;
while(1){
if(!found[j]) break;
j = rand() % 10;
}
found[j] = 1;
printf("%s\n", arr[j]);
}
return 0;
}

Need Help software is not exactly performs the required

Hello friends I need your help.
My program is such an array size 1000 where the numbers should be between 0-999. These numbers should be determined randomly (rand loop) and the number must not be repeated. Would be considered the main part, I have to count how many times I used rand().
My idea is that: one loop where it initializes all the 1000 numbers, and if in this loop they check whether the number appears twice, if the number appears twice is set it again until that not appear twice (maybe this is not the best way but ...)
It is my exercise (Here I need your help)-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int const arr_size = 1000;
int i, j, c;
int arr[arr_size];
int loop = 0;
for(i = 0; i<arr_size; i++)
{
arr[i] = rand() % 1000;
loop++;
if (arr[i] == arr[i - 1])
{
arr[i] = rand() % 1000;
loop++;
}
}
printf("%d\n",loop);
}
So if anyone can give me advice on how I can make it work I appreciate your help.
Thanks.
As suggested, shuffling the set will work but other indirect statistical quantities might be of interest, such as the distribution of the loop variable as a function of the array index.
This seemed interesting so I went ahead and plotted the distribution of the loop as a function of the array index, which generally increases as i increases. Indeed, as we get near the end of the array, the chance of getting a new random number that is not already in the set decreases (and hence, the value of the loop variable increases; see the code below).
Specifically, for an array size = 1000, I recorded the non-zero values generated for loop (there were around 500 duplicates) and then made a plot vs the index.
The plot looks like this:
The code below will produce an array with the unique random values, and then calculate the value for loop. The loop values could be stored in another array and then saved for later analysis, but I didn't include that in the code below.
Again, I'm not exactly sure this fits the application, but it does return information that would not necessarily be available from an approach using a shuffle algorithm.
NOTE: some folks expressed concerns about how long this might take but it runs pretty quick, on my 2011 Macbook Pro it took a about a second for an array size of 1000. I didn't do a big-O analysis as a function of the array size, but that would be interesting too.
NOTE 2: its more elegant to use recursion for the numberInSet() function but it seemed best to keep simple.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h> /* If C99 */
const int ARR_SIZE = 1000;
/* Check if the number is in the set up to the given position: */
bool numberInSet(int number, int* theSet, int position);
int main()
{
int* arr = malloc(sizeof(int)*ARR_SIZE);
srand((unsigned int)time(NULL));
/* Intialize array with rand entries, possibly duplicates: */
for(int i = 0; i < ARR_SIZE; i++)
arr[i] = rand() % ARR_SIZE;
/* Scan the array, look for duplicate values, replace if needed: */
for(int i = 0; i < ARR_SIZE; i++) {
int loop = 0;
while ( numberInSet(arr[i], arr, i-1) ) {
arr[i] = rand() % ARR_SIZE;
loop++;
}
/* could save the loop values here, e.g., loopVals[i] = loop; */
}
for(int i = 0; i < ARR_SIZE; i++)
printf("i = %d, %d\n",i,arr[i]);
/* Free the heap memory */
free(arr);
}
bool numberInSet(int number, int* theSet, int position) {
if (position < 0)
return false;
for(int i = 0; i <= position; i++)
if (number == theSet[i])
return true;
return false;
}
To make sure all random number you get in the same program are different, you must seed once the random generator:
srand (time(NULL)); //seed the random generator
//in the loop, rand will use the seeded value
rand() % 1000

Sorting an array of unique random numbers at insertion

I found a piece of code that works well to fill an array with a unique random numbers.
My problem now is, that I want to sort these numbers, but not after the array is full but
as new numbers are being inserted. So as each new number is inserted into the array, if finds the position it is meant to be in. The code I have for creating unique random numbers is below, thank you in advance:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define MAX 2000 // Values will be in the range (1 .. MAX)
static int seen[MAX]; // These are automatically initialised to zero
// by the compiler because they are static.
static int randomNum[1000];
int main (void) {
int i;
srand(time(NULL)); // Seed the random number generator.
for (i=0; i<1000; i++)
{
int r;
do
{
r = rand() / (RAND_MAX / MAX + 1);
}
while (seen[r]);
seen[r] = 1;
randomNum[i] = r + 1;
}
for (i=0; i<1000; i++)
cout << randomNum[i] << endl;
return 0;
}
You're looking for insertion sort.
Once you got that working, you should switch to binary insertion sort. Binary insertion sort is much faster if the array is big.

Resources