Skip to content

Instantly share code, notes, and snippets.

@simonemarra
Created January 10, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonemarra/318722c8045ed2c75d5162be1b3eb24b to your computer and use it in GitHub Desktop.
Save simonemarra/318722c8045ed2c75d5162be1b3eb24b to your computer and use it in GitHub Desktop.
C code random in range (int8_t result may be changed with other values as well). Prints results on console - tested with GCC and Code::Blocks
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <time.h>
#define _MIN_ -10
#define _MAX_ 50
#define _RANGE_ _MAX_-_MIN_
int8_t min = _MIN_;
int8_t max = _MAX_;
uint16_t rangeArray[_RANGE_];
static int8_t randInRangeInt8(int8_t min, int8_t max)
{
int8_t res = min + rand() / (RAND_MAX / (max - min + 1) + 1);
return res;
}
int main()
{
printf("Random in range test!\n");
memset(rangeArray, 0, _RANGE_);
srand(time(NULL));
uint32_t t;
for(t = 0; t < 5000; t++)
{
int8_t res = randInRangeInt8(min, max);
if((res < min) || (res > max))
{
printf("ERROR!!!! res=%d, iterator t=%d\r\n", res, t);
return -1;
}
else
{
if(rangeArray[res-_MIN_] < 65535)
rangeArray[res-_MIN_]++;
}
}
printf("\r\n\r\n");
for(t = 0; t < _RANGE_; t++)
{
printf("[%.3d]:%.3d => ", t+_MIN_, rangeArray[t]);
int val = rangeArray[t];
while(val > 0)
{
printf("*");
val--;
}
printf("\r\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment