Random numbers that do not match each other - c

I want to produce different numbers with C.
We can generate a random number using the stdlib library and the srand function.
For example; I want to produce a random number between 0 and 5.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[3];
srand(time(NULL));
for(i = 0; i < n; i++)
{
array[i] = rand() % 5;
printf("%d\n", array[i]);
}
return 0;
But the same numbers may coincide here.Like this:
2
4
4
1
How can I prevent this?

Maybe you can use something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[4];
// Fill an array with possible values
int values[5] = {0, 1, 2, 3, 4};
srand(time(NULL));
for(i = 0; i < n; i++)
{
int t1 = rand() % (5-i); // Generate next index while making the
// possible value one lesser for each
// loop
array[i] = values[t1]; // Assign value
printf("%d\n", array[i]);
values[t1] = values[4-i]; // Get rid of the used value by
// replacing it with an unused value
}
return 0;
}

Instead of random number you can generate random non-zero shift from the previous number:
#include <stdio.h>
#include <stdlib.h>
int myrand() {
static int prev = -1;
if (prev < 0)
prev = rand() % 5;
prev = (prev + 1 + rand() % 4) % 5;
return prev;
}
int main(void) {
int i;
for (i = 0; i < 20; i++)
printf("%d\n", myrand());
}

Related

I am trying to print a random character from an array by using rand()

Hello all I want to write a program to randomly choose a character from an array, so far I have come up with this code. I get an Error message help...Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) at the last printf()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int lower = 1, upper = 6;
int test;
srand((unsigned int)time(0));
char* placeArray[]={"Renti","Mosxato","Tavros","Kallithea","Petralona","Thisio"};
int i, num;
for (i=0;i<6;i++){
num=(rand() % (upper - lower + 1)) + lower;
test=(int)num;
printf("%d ",num);
printf("%s\n",placeArray[num]);
}
return 0;
}
num should be num-1 in the last printf, because the range of the elements in the array is 0 to 5, as shown below
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int lower = 1, upper = 6;
int test;
srand((unsigned int)time(0));
char * placeArray[]= {"Renti", "Mosxato", "Tavros", "Kallithea", "Petralona", "Thisio"};
int i, num;
for (i = 0; i < 6; i++){
num = (rand() % (upper - lower + 1)) + lower;
test = (int)num;
printf("%d ", num);
printf("%s\n", placeArray[num - 1]);
}
return 0;
}

how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}

Is there a way to stop my program from printing duplicates?

I wrote this program, which is supposed to print all combinations whose sum is equal to a given number.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "combinations.h"
int c = 0;
void findsubsets(unsigned int *numnumbers, int n, int i) {
int j;
if (i < 0)
return;
int sum = 0;
for (j = 0; j < n; j++) {
if (i & (1 << j)) {
sum = sum + numnumbers[j];
}
}
if (sum == target) {
c++;
for (j = 0; j < n; j++) {
if (i & (1 << j))
printf("%u ", numnumbers[j]);
}
printf("\n");
}
}
int main() {
unsigned int iterations = pow(2, VECTOR_SIZE);
for (int i = 0; i < iterations - 1 ; i++)
findsubsets(numbers, VECTOR_SIZE, i);
return 0;
}
//header file next
#ifndef Header_h
#define Header_h
#define VECTOR_SIZE 6
unsigned int numbers[VECTOR_SIZE] = {1, 2, 4, 3, 2, 1};
unsigned int target = 4;
#endif /* Header_h */
However, if as in the example in the header, a number is repeated in the given vector, then it prints out some combinations that include the same numbers. Is there a way to prevent it from doing so? I'm thinking maybe I should use linked lists (which would include all the valid combinations and then compare them, eliminate the ones that are equal, and print out the rest) but I'm pretty sure that would be very time-consuming to write and maybe not very efficient. Is there a less complicated way to do this?
Thank you

how to get my random function to work?

The random function is not working in the parameters set and I do not know why. Can anyone help? I need random numbers between 18 and 38 and I can't seem to get that and I do not know why.
Here's my code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
}typedef tires;
void getTireInformation(tires*, int);
void tirePressure(tires*, int);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", &(ptire + i) ->Manufacturer);
}
printf("all tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n",(ptire +i) ->Manufacturer);
}
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
srand(time(NULL));
ptire = rand()%(max - min)-min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}
Edit: Here's my updated function after making the suggested fixes
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
ptire = rand()%(max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}
It's not necessary to call srand(time(NULL)); every time it generates a random number. Put that in main(), before any function call.
Then change
rand() % (max - min) - min;
to
rand() % (max - min + 1) + min;
Say max = 3 and min = 1, you need rand() % 3 + 1 to generate a random number from 1 to 3 inclusively.
There is another problem, which have nothing to do with random number generating: The random numbers generated is assigned to ptire, that is, you are assigning a tires* with an int!
I've refined your code. Hope it will work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
} typedef tires;
// Prototypes
void getTireInformation(tires*, size_t);
void tirePressure(tires*, size_t);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
srand(time(NULL));
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, size_t size)
{
size_t i = 0;
for (i = 0; i < size; i++)
{
printf("Please enter the maker of the tire: \n");
scanf("%s", (ptire + i) -> Manufacturer); // just use str. &str actually causes undefined bahavior
}
printf("All tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n", (ptire +i) -> Manufacturer);
}
void tirePressure(tires* ptire, size_t size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
(ptire + i) ->tire_pressure[0] = rand() % (max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure[0]);
}
}
And here is the result when I run it:
Please enter the maker of the tire:
qwert
Please enter the maker of the tire:
fewqwe
Please enter the maker of the tire:
hcgexf
Please enter the maker of the tire:
zrbghcr
All tire make you entered ...just for verification:
qwert
fewqwe
hcgexf
zrbghcr
22
34
31
31
All numbers are between 18 to 38 now. Note that tire_pressure is an array containing two ints. Without knowing your purpose, I just gave random numbers to its first element.

How to generate random numbers in C two colons?

I need in c code that generates two numbers in horizontally...so that i can get token numbers for my login system.
I need that i get this:
token=0.152644,0.429187
so in example i have token= and random generated numbers that have at beginning 0. and then 6 random generated numbers separated with , sign.
How to get get this in C?
I have try this code but it does not give me what i want_
#include <stdio.h>
#include <string.h>
typedef
union
{
char tmp[sizeof(unsigned long long)];
unsigned long long myll;
} ll_t;
unsigned long long llrand(void)
{
FILE *in=fopen("/dev/urandom", "r");
ll_t ll_u;
fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
fclose(in);
return ll_u.myll;
}
int main()
{
char tmp1[64]={0x0};
char working[64]={0x0};
int i=0;
for(i=0; i< 1; i++)
{
while(strlen(tmp1) < 6)
{
sprintf(working, "%lu", llrand() );
strcat(tmp1, working);
}
tmp1[6]=0x0;
printf("%s\n", tmp1);
*tmp1=0x0;
}
return 0;
}
From output i get this:
747563
102595
Can code be simple and short?
You can use rand() function:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int randomNumber(int min, int max)
{
/* generate secret number between min and max: */
int res = rand() % (max-min+1) + min;
return res;
}
int main()
{
int i = 0;
srand (time(NULL));
for (i=0; i<100; i++)
printf("%d ", randomNumber(10, 1000000));
return 0;
}
That is full detail for rand():
http://www.cplusplus.com/reference/cstdlib/rand/
Here is the code that is working perfect:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n1, n2;
time_t t;
srand((unsigned) time(&t));
n1 = rand() % 1000000 + 1;
n2 = rand() % 1000000 + 1;
printf("token=0.%d,0.%d\n", n1, n2);
return 0;
}
And output is:
token=0.289384,0.930887
A propose a different approach. Instead of generating 2 numbers and format them into the output string, generate 12 different digits and put them directly in place.
srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
for (int k = 0; k < 6; k++) {
output[9 * n + 8 + k] = rand() % 10 + '0';
// you might want to write a function that deals with rand() bias
}
}
puts(output);

Resources