0

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.

Howlan
  • 11
  • 2
  • So, the user input is the "size" of the generated random (hex) number. Is `0x000` a valid output, given an input of 3? Is this an homework with weird restrictions or constraints we should know about? – Bob__ Dec 04 '21 at 12:28

2 Answers2

0

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?.

brc-dd
  • 10,788
  • 3
  • 47
  • 67
-2

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;
}
Howlan
  • 11
  • 2
  • 1
    `g` - `z` are not valid hex digits. Also, _"As the seed is unsigned, it will not go below 0."_, is not a correct explanation of why `rand()` won't return negative integers. – brc-dd Dec 04 '21 at 12:20
  • Using the C rand library is bad. See https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad – bolov Dec 04 '21 at 14:08