Reputation: 319
I have code that generates a random number using a Left Feedback Shift Register that I got off the internet:
#define POLY_MASK_32 0xB4BCD35C
#define POLY_MASK_31 0x7A5BC2E3
#include <iostream>
typedef unsigned int uint;
uint lfsr32, lfsr31;
int shift_lfsr(uint *lfsr, uint polymonial_mask)
{
int feedback;
feedback = *lfsr & 1;
*lfsr >>= 1;
if (feedback == 1)
*lfsr ^= polymonial_mask;
return *lfsr;
}
void init_lfsrs(void)
{
lfsr32 = 0xABCDE; //seed values
lfsr31 = 0x23456789;
}
int get_random(void)
{
/*this random number generator shifts the 32-bit LFSR twice before XORing
it with the 31-bit LFSR. the bottom 16 bits are used for the random number*/
shift_lfsr(&lfsr32, POLY_MASK_32);
return(shift_lfsr(&lfsr32, POLY_MASK_32) ^ shift_lfsr(&lfsr31, POLY_MASK_31));
}
void main(void)
{
int random_value[10];
init_lfsrs();
for(int i = 0; i < 10; i++)
{
random_value[i] = get_random();
std::cout << random_value[i] << std::endl;
}
}
I dont fully unerstand whats going on here but I know that it will produce a 32-bit number in a non repeating sequence. I think it then takes the first 16-bits to be the number displayed.
What I am wanting to do is produce a number between 1-6 from this...anyone able to help out?
Edit I was also going to change the 2 seed values to an srand(time) rand() number so that it doesn't start the same every time. is this right and how would i go about that?
Upvotes: 0
Views: 3348
Reputation: 1123
To produce a random number between 1 and 6, do this
int myRandomNumber = 1 + (random_value[i] % 6);
Why does this work?
random_value[i] % 6
will produce a value between 0 and 5, so we add 1 to it to get a value between 1 and 6.
Read up on the modulus operator
http://www.cprogramming.com/tutorial/modulus.html
In general, to produce a random number in some closed set [a, b], you would do
int myRandomNumber = a + ( random_value[i] % (b - a + 1) )
Upvotes: 1