Home > database >  Generate a randomised hex number based on user input
Generate a randomised hex number based on user input

Time:12-05

I'm writing a program that generates a randomised colour, sourced from a hex number based on a users numerical input. User input is 3, the hex number is 0x??? User input is 4, the hex number is 0x???? The values after '0x' are random each time the program is ran.

CodePudding user response:

Code

If you want integer values instead of strings you can do something like this:

#include <iostream>
#include <random>

int main() {

    std::random_device rd;
    std::mt19937_64 gen(rd());

    std::uint16_t n;
    std::cin >> n;

    auto R = 1ULL << (n * 4), L = (R >> 4) - (n == 1);
    std::uniform_int_distribution<std::uint64_t> dist(L, R - 1);

    std::cout << "0x" << std::hex << dist(gen) << "\n";
}

Caveats

  • This will only work for 0<n<16 as larger numbers can't be stored in standard integer types.

  • This doesn't consider 0x00 a 2 digit hex number as 0x0 == 0x00 == 0x000 == ....

Explanation

Upper/Right Limit of Range to Generate = R - 1
R = 0x1000... <-- n trailing zeros
  = 16 ** n (in decimal)

Lower/Left Limit of Range to Generate = L
L = 0x0 if n is 1 otherwise:
  = 0x100... <-- (n - 1) trailing zeros

References

Based on Generating random integer from a range, C cout hex values?.

CodePudding user response:

To achieve this:
A simple for loop where the condition is based off of the user input. Seed the random value from time, once.
Then produce a random value, which takes from the array (consisting of all the possible hex number values)
Concat that onto the starting hex value '0x'
A modulus value has been used to set a maximum value that the random value can be.
As the seed is unsigned, it will not go below 0.

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main() {
  srand((unsigned) time(0));
  int userInput = 0;
  char array[36] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  string hexNumber = "0x";
  std::cin >> userInput;
  for(int i = 0; i < userInput; i  )
  {
    hexNumber = hexNumber   array[(rand() % 35)];
  }
  
  cout << hexNumber << endl;
}
  •  Tags:  
  • c
  • Related