How to solve infinite loop for generated music? - c

I have a program that I want to create a randomly generated bar of music (4 beats to a bar, using C Major scale). However, I'm having trouble understanding the math and keep overflowing my do while loop, creating more than 4 notes to the bar which I want to avoid.
I am using aServe, which was created by my tutor, but basically opens a stream to an Oscillator that plays the arguments I've commented.
/* Program for randomly written bar of 4/4 in C Major */
#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <stdlib.h>
//macros
#define SEMIBREVE (1.0)
#define MINIM (1.0/2)
#define CROTCHET (1.0/4)
#define QUAVER (1.0/8)
#define SEMIQUAVER (1.0/16)
#define DEMISEMIQUAVER (1.0/32)
#define C (261.63)
#define D (293.66)
#define E (329.63)
#define F (349.23)
#define G (391.99)
#define A (440.00)
#define B (493.88)
int millisec(int bpm, double note) {
return (int)(
60 /* seconds */
* 1000 /* milliseconds per second */
* 4 /* crotchets per semibreve */
* note
/ bpm
);
}
int main()
{
int bpm = 120; //BPM Value
double Length[] = {SEMIBREVE, MINIM, CROTCHET, QUAVER, SEMIQUAVER, DEMISEMIQUAVER}; //Array of Note Lengths
double Pitch[] = {C, D, E,F, G, A, B}; //Array of CMajor Scale Freq
int randLength = (rand() % 6); //random positions for note length
int randPitch = ( rand() % 7); //random positions for note pitch
double barTotal = 0; //amount of bar currently completed
do {
if(barTotal < 1) //if bar total is smaller than 1
{
barTotal = Length[randLength] + barTotal; //add note to total
aserveOscillator(0, Pitch[randPitch], 1, 2); //Starts stream to oscialltor
//aserveOscillator(Index,Frequency,Amplitude,WaveType);
aserveSleep(millisec(bpm, Length[randLength])); //play the notes for the length of time specified in milliseconds
randLength = (rand() % 6); //prepare next random note
randPitch = (rand() % 7); //prepare next random pitch
//Output
printf("Note: ");
printf("%lf", Pitch[randPitch]);
printf("\n For: ");
printf("%lf", Length[millisec(bpm,randLength)]);
printf("\n With Bar Total: ");
printf("%lf", barTotal);
printf("\n\n");
}
else
{
if(barTotal != 1) //if bar total is bigger than 4
{
randLength = (rand() % 6); //try another number
}
}
} while (barTotal != 1); //will stop once reaches 4
return 0;
}

Consider thinking about the problem differently. Think of a bar as "n" slots where n is the most granular note type you have. So in your case a bar is a group of 32 slots. Rather than representing your numbers as fractions, use integral types to show how many of those "slots" each takes. So a DEMISEMIQUAVER takes 1 slot, which can be represented as an int rather than being (1.0 / 32.0) which introduces some potentially ugly issues.
Once you do this the solution is more straightforward:
1) How many slots are left in the current bar?
2) Choose a random note from a pool of notes smaller than the remaining slots
3) Recalculate how much room is left after adding the new note
4) If the remaining room is zero, proceed to the next bar.
Below is your code, adapted to this new approach. Not fully tested but it should avoid most if not all of the pitfalls discussed thus far.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//macros
#define SEMIBREVE (32)
#define MINIM (16)
#define CROTCHET (8)
#define QUAVER (4)
#define SEMIQUAVER (2)
#define DEMISEMIQUAVER (1)
#define C (261.63)
#define D (293.66)
#define E (329.63)
#define F (349.23)
#define G (391.99)
#define A (440.00)
#define B (493.88)
int GetMaxIndex(int remainingLength)
{
// Returns the largest upper bound of the Length array that
// should be considered based on how much room remains in
// the current bar.
int result;
if(remainingLength == 32) result = 5;
if(remainingLength < 32) result = 4;
if(remainingLength < 16) result = 3;
if(remainingLength < 8) result = 2;
if(remainingLength < 4) result = 1;
if(remainingLength < 2) result = 0;
return result;
}
int main()
{
double Pitch[] = {C, D, E,F, G, A, B}; //Array of CMajor Scale Freq
int bpm = 120; //BPM Value
int Length[] = {DEMISEMIQUAVER, SEMIQUAVER, QUAVER, CROTCHET, MINIM, SEMIBREVE}; //Array of Note Lengths
char* Labels[] = {"DEMISEMIQUAVER (Thirty Second)", "SEMIQUAVER (Sixteenth)", "QUAVER (Eighth)", "CROTCHET (Quarter)", "MINIM (Half)", "SEMIBREVE (Whole)"};
int remainingThisBar;
int barsToGenerate = 4;
int randLength = (rand() % 6); //random positions for note length
int randPitch; //random positions for note pitch
int maxIndex;
int randIndex;
srand(time(NULL));
for(int barNumber = 0; barNumber < barsToGenerate; barNumber++)
{
printf("Beginning bar: %i\n", barNumber);
remainingThisBar = 32;
while(remainingThisBar > 0)
{
maxIndex = GetMaxIndex(remainingThisBar); // What is the biggest note index we still have room for?
randIndex = maxIndex == 0 ? 0 : (rand() % maxIndex); // Get a random note between 0 and maxIndex
randPitch = ( rand() % 7); // Random positions for note pitch
randLength = Length[randIndex]; // Length in 32nds
remainingThisBar -= randLength;
// Output
printf("\tNote: %s # %f\n", Labels[randIndex], Pitch[randPitch]);
printf("\t32nds remaining in bar: %i\n", remainingThisBar);
printf("\n");
/* TODO - Output note via aServe*/
}
}
}

Related

A function that takes an integer and inserts zeros between its digits

The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.

C stops woking when a vaiable is multiplied and divided with double digit numbers

#include <cs50.h>
#include <stdio.h>
int main(void)
{
// TODO: Prompt for start size
int s;
do
{
s = get_int("Start size : ");
}
while (s < 9);
// TODO: Prompt for end size
int e;
do
{
e = get_int("End size : ");
}
while (e < s);
// TODO: Calculate number of years until we reach threshold
int n = s;
int y = 0;
while (n < e)
{
n = n + n / 3 - n / 4 ;
y++;
}
// TODO: Print number of years
printf("Years: %i\n", y);
}
I am able to run the above code perfectly and get the desired results. However when i try to replace the n's calculation part by simplifying the math the code stops working i.e it does not calculate what its intended to calculate and keeps the program in the input taking mode i.e it lets you type in the terminal without giving output. I replaced the n's calculation part with
n = (13 * n) / 12
Because of integer arithmetics, the expressions n = n + n / 3 - n / 4; and n = n * 13 / 12; are not equivalent: integer division rounds toward zero so for example the first expression increments n from 3 to 4 but not the second expression.
You should use floating point arithmetics for this problem:
#include <cs50.h>
#include <stdio.h>
int main(void) {
// TODO: Prompt for start size
int s;
do {
s = get_int("Start size: ");
} while (s < 9);
// TODO: Prompt for end size
int e;
do {
e = get_int("End size: ");
} while (e < s);
// Calculate number of years until we reach threshold
double n = s;
int y = 0;
while (n < e) {
n = n * 13.0 / 12.0;
y++;
}
// TODO: Print number of years
printf("Years: %i\n", y);
return 0;
}

How to generate 12 digit random number in C?

I'm trying to generate 12 digit random numbers in C, but it's always generating 10 digit numbers.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void main()
{
srand(time(NULL));
long r = rand();
r = r*100;
printf("%ld",r);
}
rand() returns an int value in the range of [0...RAND_MAX]
Based on the C spec, RAND_MAX >= 32767 and RAND_MAX <= INT_MAX.
Call rand() multiple times to create a wide value
unsigned long long rand_atleast12digit(void) {
unsigned long long r = rand();
#if RAND_MAX >= 999999999999
#elif RAND_MAX >= 999999
r *= RAND_MAX + 1ull;
r += rand();
#else
r *= RAND_MAX + 1ull;
r += rand();
r *= RAND_MAX + 1ull;
r += rand();
#endif
return r;
}
The above returns a number if the range of 0 to at least 999,999,999,999. To reduce that to only that range, code could use return r % 1000000000000;.
Using % likely does not create an balanced distribution of random numbers. Other posts address details of how to cope with that like this good one incorporated as follows.
#if RAND_MAX >= 999999999999
#define R12DIGIT_DIVISOR (RAND_MAX/1000000000000)
#elif RAND_MAX >= 999999
#define RAND_MAX_P1 (RAND_MAX+1LLU)
#define R12DIGIT_DIVISOR ((RAND_MAX_P1*RAND_MAX_P1-1)/1000000000000)
#else
#define RAND_MAX_P1 (RAND_MAX+1LLU)
#define R12DIGIT_DIVISOR ((RAND_MAX_P1*RAND_MAX_P1*RAND_MAX_P1-1)/1000000000000)
#endif
unsigned long long rand_12digit(void) {
unsigned long long retval;
do {
retval = rand_atleast12digit() / R12DIGIT_DIVISOR;
} while (retval == 1000000000000);
return retval;
}
Note that the quality of rand() is not well defined, so repeated calls may not provide high quality results.
OP's code fails if long is 32-bit as it lacks range for a 12 decimal digit values. #Michael Walz
If long is wide enough, *100 will always make the least 2 decimal digits 00 - not very random. #Alexei Levenkov
long r = rand();
r = r*100;
The result of rand is int, which means you can't get a 12 digit number directly from it.
If you need value that is always 12 digits you need to make sure values fit in particular range.
Sample below assumes that you need just some of the numbers to be 12 digits - you just need 8 extra bits - so shifting and OR'ing results would produce number in 0x7fffffffff-0 range that would often result up to 12 digit output when printed as decimal:
r = rand();
r = (r << 8) | rand();
PS: Make sure the variable that will store the result is big enough to store the 12 digit number.
My simple way to generate random strings or numbers is :
static char *ws_generate_token(size_t length) {
static char charset[] = "1234567890"; // generate numbers only
//static char charset[] = "abcdefghijklmnopqrstuvwxyz1234567890"; to generate random string
char *randomString = NULL;
if (length) {
randomString = malloc(sizeof(char) * (length + 1));
if (randomString) {
for (int n = 0; n < length; n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}
randomString[length] = '\0';
}
}
return randomString;
}
Explain the code
Create an array of chars which will contains (numbers, alphabets ...etc)
Generate a random number between [0, array length], let's name it X.
Get the character at random X position in the array of chars.
finally, add this character to the sequence of strings (or numbers) you want to have in return.
How to use it ?
#define TOKEN_LENGTH 12
char *token;
token = ws_generate_token(TOKEN_LENGTH);
conversion from string to int
int token_int = atol(token);
dont forget !
free(token); // free the memory when you finish
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
time_t t;
n = 5;
/* Intializes random number generator int range */
srand((unsigned) time(&t));
/* Print 5 random numbers from 50 to back
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 50);
}
return(0);
}

How to generate random 64-bit unsigned integer in C

I need generate random 64-bit unsigned integers using C. I mean, the range should be 0 to 18446744073709551615. RAND_MAX is 1073741823.
I found some solutions in the links which might be possible duplicates but the answers mostly concatenates some rand() results or making some incremental arithmetic operations. So results are always 18 digits or 20 digits. I also want outcomes like 5, 11, 33387, not just 3771778641802345472.
By the way, I really don't have so much experience with the C but any approach, code samples and idea could be beneficial.
Concerning "So results are always 18 digits or 20 digits."
See #Thomas comment. If you generate random numbers long enough, code will create ones like 5, 11 and 33387. If code generates 1,000,000,000 numbers/second, it may take a year as very small numbers < 100,000 are so rare amongst all 64-bit numbers.
rand() simple returns random bits. A simplistic method pulls 1 bit at a time
uint64_t rand_uint64_slow(void) {
uint64_t r = 0;
for (int i=0; i<64; i++) {
r = r*2 + rand()%2;
}
return r;
}
Assuming RAND_MAX is some power of 2 - 1 as in OP's case 1073741823 == 0x3FFFFFFF, take advantage that 30 at least 15 bits are generated each time. The following code will call rand() 5 3 times - a tad wasteful. Instead bits shifted out could be saved for the next random number, but that brings in other issues. Leave that for another day.
uint64_t rand_uint64(void) {
uint64_t r = 0;
for (int i=0; i<64; i += 15 /*30*/) {
r = r*((uint64_t)RAND_MAX + 1) + rand();
}
return r;
}
A portable loop count method avoids the 15 /*30*/ - But see 2020 edit below.
#if RAND_MAX/256 >= 0xFFFFFFFFFFFFFF
#define LOOP_COUNT 1
#elif RAND_MAX/256 >= 0xFFFFFF
#define LOOP_COUNT 2
#elif RAND_MAX/256 >= 0x3FFFF
#define LOOP_COUNT 3
#elif RAND_MAX/256 >= 0x1FF
#define LOOP_COUNT 4
#else
#define LOOP_COUNT 5
#endif
uint64_t rand_uint64(void) {
uint64_t r = 0;
for (int i=LOOP_COUNT; i > 0; i--) {
r = r*(RAND_MAX + (uint64_t)1) + rand();
}
return r;
}
The autocorrelation effects commented here are caused by a weak rand(). C does not specify a particular method of random number generation. The above relies on rand() - or whatever base random function employed - being good.
If rand() is sub-par, then code should use other generators. Yet one can still use this approach to build up larger random numbers.
[Edit 2020]
Hallvard B. Furuseth provides as nice way to determine the number of bits in RAND_MAX when it is a Mersenne Number - a power of 2 minus 1.
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
#define RAND_MAX_WIDTH IMAX_BITS(RAND_MAX)
_Static_assert((RAND_MAX & (RAND_MAX + 1u)) == 0, "RAND_MAX not a Mersenne number");
uint64_t rand64(void) {
uint64_t r = 0;
for (int i = 0; i < 64; i += RAND_MAX_WIDTH) {
r <<= RAND_MAX_WIDTH;
r ^= (unsigned) rand();
}
return r;
}
If you don't need cryptographically secure pseudo random numbers, I would suggest using MT19937-64. It is a 64 bit version of Mersenne Twister PRNG.
Please, do not combine rand() outputs and do not build upon other tricks. Use existing implementation:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html
Iff you have a sufficiently good source of random bytes (like, say, /dev/random or /dev/urandom on a linux machine), you can simply consume 8 bytes from that source and concatenate them. If they are independent and have a linear distribution, you're set.
If you don't, you MAY get away by doing the same, but there is likely to be some artefacts in your pseudo-random generator that gives a toe-hold for all sorts of hi-jinx.
Example code assuming we have an open binary FILE *source:
/* Implementation #1, slightly more elegant than looping yourself */
uint64_t 64bitrandom()
{
uint64_t rv;
size_t count;
do {
count = fread(&rv, sizeof(rv), 1, source);
} while (count != 1);
return rv;
}
/* Implementation #2 */
uint64_t 64bitrandom()
{
uint64_t rv = 0;
int c;
for (i=0; i < sizeof(rv); i++) {
do {
c = fgetc(source)
} while (c < 0);
rv = (rv << 8) | (c & 0xff);
}
return rv;
}
If you replace "read random bytes from a randomness device" with "get bytes from a function call", all you have to do is to adjust the shifts in method #2.
You're vastly more likely to get a "number with many digits" than one with "small number of digits" (of all the numbers between 0 and 2 ** 64, roughly 95% have 19 or more decimal digits, so really that is what you will mostly get.
If you are willing to use a repetitive pseudo random sequence and you can deal with a bunch of values that will never happen (like even numbers? ... don't use just the low bits), an LCG or MCG are simple solutions. Wikipedia: Linear congruential generator can get you started (there are several more types including the commonly used Wikipedia: Mersenne Twister). And this site can generate a couple prime numbers for the modulus and the multiplier below. (caveat: this sequence will be guessable and thus it is NOT secure)
#include <stdio.h>
#include <stdint.h>
uint64_t
mcg64(void)
{
static uint64_t i = 1;
return (i = (164603309694725029ull * i) % 14738995463583502973ull);
}
int
main(int ac, char * av[])
{
for (int i = 0; i < 10; i++)
printf("%016p\n", mcg64());
}
I have tried this code here and it seems to work fine there.
#include <time.h>
#include <stdlib.h>
#include <math.h>
int main(){
srand(time(NULL));
int a = rand();
int b = rand();
int c = rand();
int d = rand();
long e = (long)a*b;
e = abs(e);
long f = (long)c*d;
f = abs(f);
long long answer = (long long)e*f;
printf("value %lld",answer);
return 0;
}
I ran a few iterations and i get the following outputs :
value 1869044101095834648
value 2104046041914393000
value 1587782446298476296
value 604955295827516250
value 41152208336759610
value 57792837533816000
If you have 32 or 16-bit random value - generate 2 or 4 randoms and combine them to one 64-bit with << and |.
uint64_t rand_uint64(void) {
// Assuming RAND_MAX is 2^31.
uint64_t r = rand();
r = r<<30 | rand();
r = r<<30 | rand();
return r;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
unsigned long long int randomize(unsigned long long int uint_64);
int main(void)
{
srand(time(0));
unsigned long long int random_number = randomize(18446744073709551615);
printf("%llu\n",random_number);
random_number = randomize(123);
printf("%llu\n",random_number);
return 0;
}
unsigned long long int randomize(unsigned long long int uint_64)
{
char buffer[100] , data[100] , tmp[2];
//convert llu to string,store in buffer
sprintf(buffer, "%llu", uint_64);
//store buffer length
size_t len = strlen(buffer);
//x : store converted char to int, rand_num : random number , index of data array
int x , rand_num , index = 0;
//condition that prevents the program from generating number that is bigger input value
bool Condition = 0;
//iterate over buffer array
for( int n = 0 ; n < len ; n++ )
{
//store the first character of buffer
tmp[0] = buffer[n];
tmp[1] = '\0';
//convert it to integer,store in x
x = atoi(tmp);
if( n == 0 )
{
//if first iteration,rand_num must be less than or equal to x
rand_num = rand() % ( x + 1 );
//if generated random number does not equal to x,condition is true
if( rand_num != x )
Condition = 1;
//convert character that corrosponds to integer to integer and store it in data array;increment index
data[index] = rand_num + '0';
index++;
}
//if not first iteration,do the following
else
{
if( Condition )
{
rand_num = rand() % ( 10 );
data[index] = rand_num + '0';
index++;
}
else
{
rand_num = rand() % ( x + 1 );
if( rand_num != x )
Condition = 1;
data[index] = rand_num + '0';
index++;
}
}
}
data[index] = '\0';
char *ptr ;
//convert the data array to unsigned long long int
unsigned long long int ret = _strtoui64(data,&ptr,10);
return ret;
}

Generating random integer values within a range in C [duplicate]

This question already has answers here:
How to generate a random integer number from within a range
(11 answers)
Closed 9 years ago.
How do I go about generating random integer values between a range (in this case 1-12 including 1 and 12) in the C language?
I've read about seeding (srand()) and using rand() within a range but am unsure about how to go about it.
Edit: Here is what I have so far
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
// Craps Program
// Written by Kane Charles
// Lab 2 - Task 2
// 7 or 11 indicates instant win
// 2, 3 or 12 indicates instant los
// 4, 5, 6, 8, 9, 10 on first roll becomes "the point"
// keep rolling dice until either 7 or "the point is rolled"
// if "the point" is rolled the player wins
// if 7 is rolled then the player loses
int wins = 0, losses = 0;
int r, i;
int N = 1, M = 12;
int randomgenerator();
main(void){
/* initialize random seed: */
srand (time(NULL));
/* generate random number 10,000 times: */
for(i=0; i < 10000 ; i++){
int r = randomgenerator();
if (r = 7 || 11) {
wins++;
}
else if (r = 2 || 3 || 12) {
losses++;
}
else if (r = 4 || 5 || 6 || 8 || 9 || 10) {
int point = r;
int temproll;
do
{
int temproll = randomgenerator();
}while (temproll != 7 || point);
if (temproll = 7) {
losses++;
}
else if (temproll = point) {
wins++;
}
}
}
printf("Wins\n");
printf("%lf",&wins);
printf("\nLosses\n");
printf("%lf",&losses);
}
int randomgenerator(){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
return r;
}
The simple way is
#include <stdlib.h>
#include <sys/time.h>
int main(void)
{
struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
int a = 1, b = 12;
int val = a + (b-a) * (double)rand() / (double)RAND_MAX + 0.5;
return 0;
}
Edit, since someone asked: You really do have to use floating point arithmetic to get this to come out right (or as right as it can given rand()'s limitations such as they are). Any solution which relies purely on integer arithmetic and rand() will of necessity use \ or %, and when this happens you will get roundoff error--where c and d are declared int and c = 5 and d = 2, for example, c/d == 2 and d/c == 0. When comes to sampling from a range, what happens is that in compressing the range [0, RAND_MAX] to [a, b], you have to do some kind of division operation since the former is so much larger than the latter. Then roundoff creates bias (unless you get really lucky and things evenly divide). Not a truly thorough explanation but I hope that conveys the idea.
You should use: M + rand() / (RAND_MAX / (N - M + 1) + 1)
Don't use rand() % N (which tries to return numbers from 0 to N-1). It is poor, because the low-order bits of many random number generators are distressingly non-random. (See question 13.18.)
Example code:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int r, i;
int M = 1,
N = 12;
/* initialize random seed: */
srand (time(NULL));
/* generate number between 1 and 12: */
for(i=0; i < 10 ; i++){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
printf("\n%d", r);
}
printf("\n") ;
return EXIT_SUCCESS;
}
It's working here at codepad.

Resources