Skip to content

Instantly share code, notes, and snippets.

@gboncoffee
Created September 11, 2023 00:00
Show Gist options
  • Save gboncoffee/fa9312d273868cf16c3a8307a6eb0c3f to your computer and use it in GitHub Desktop.
Save gboncoffee/fa9312d273868cf16c3a8307a6eb0c3f to your computer and use it in GitHub Desktop.
TCC script to generate random numbers.
#!/usr/bin/env -S tcc -run
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
/*
* Copyright (C) 2023 Gabriel de Brito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Quick way of generating random numbers ;)
*/
void generate_numbers(long min, long max, long n)
{
long mod = max - min + 1;
long r;
for (; n > 0; n--) {
r = (random() % mod) + min;
printf("%ld\n", r);
}
}
void init_pool()
{
long seed = (long) time(NULL);
FILE *urandom = fopen("/dev/urandom", "r");
if (urandom != NULL) {
long r;
fread(&r, 1, 8, urandom);
seed *= (long) r;
fclose(urandom);
}
srand(seed);
}
void safely_parse_long(char *str, long *n)
{
long tmp;
errno = 0;
int i = sscanf(str, "%ld", &tmp);
if (i)
*n = tmp;
}
int main(int argc, char *argv[])
{
long min = 0;
long max = 100;
long n = 1;
if (argc >= 2) {
errno = 0;
safely_parse_long(argv[1], &min);
if (argc >= 3) {
errno = 0;
safely_parse_long(argv[2], &max);
if (argc >= 4) {
errno = 0;
safely_parse_long(argv[3], &n);
}
}
}
init_pool();
generate_numbers(min, max, n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment