you are in C++, so DO NOT USE C stuff like rand(). Not only because rand issue by itself (see later), but because C++ is a very different beast than C than come with better solution to many problems. I suggest you to skim over "the C++ coding standard" when in doubt: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Also you are importing the namespace and not using it, so just dont. In general; the coding standard suggest to use it ONLY if you make heavy use of std stuff, and in your case where you mix C++ and C stuff, nameclash between C lib and std is very likely
rand() % 26
This is a bad idea and screw up the random distribution, unless your modulo happen to be exactly modulo of RAND_MAX. In C++ use std::uniform_int_distribution
ok, but you notice you have an array of 27 but 26 letter, because the End of String; but if you change the array, maybe you add some accent or even lowercase latter, you have to remember to change 2 places in the code.
If you declare the array first, then you can use sizeof(letters) - 1 to obtain your modulo values, also i would drop the [27] and replace it with [], as now it all depends on sizeof.
If instead you want strict 26 letter, you should create a constepr value with it, and use it everywhere, and enable the warning (i think "pedantic") that will generate a warning if your initialization does not match the array declared size, and also -werror that make any warning into error is a very good idea for beginner.
For a beginner the idea is more important than trying to shave a few bytes off the source code.
Does it work? If so then it's good to a point, the getting of the random number is another matter but that's best left to the spooks who love their RNG
Obviously it's only got a small spread of numbers as 64 chars is good enough for most people unless you are using a printer then it gets more fun but I was used to using a mainframe where one of the printers only needed 6 bits as it made the lines per minute a lot more so long as you didn't want lowercase which was fine for cobol listings for the Devs.
Here, we are using the /dev/random character special device which is a cryptographically secure random byte generator.
If you'd like, you can use /dev/urandom if you care about a nonblocking application. /dev/random is only suitable for applications that need high quality randomness, and can afford indeterminate delays.
The /dev/random device is a legacy interface which dates back to a time where the cryptographic primitives used in the implementation of /dev/urandom were not widely trusted. Nowadays, it is common to choose /dev/urandom unless high quality absolute randomness is required.
/dev/random will return random bytes only within the estimated number of bits of fresh noise in the entropy pool, blocking if necessary (not returning any random bytes until fresh noise is available).
while (strlen($token)<$length) $token .= $charset[(mt_rand(0,(strlen($charset)-1)))];
Keep in mind that the token created in my case is not and should not be used for security purposes, but merely a case of "Here's this thing I spit out that's somewhat unique and therefore unlikely to appear by happenchance, go put it somewhere and tell me when you did it so I can verify that it was actually you who did the thing."
preprocessor is really messy, and it has no concept of scope or namespaces, meaning that they can very easily clutter up your code. they should absolutely not be used for data, and at most be reserved for enabling / disabling code and even then, it should be done at the compiler / configure level, rather than via #define in your code
in C++ there's better ways around basically everything preprocessors give you (other than the example of enabling / disabling code like i said, maybe) and you should use those (ie constexpr)
If you have a set of characters whose ASCII values aren't contiguous, the way you went about it is completely sensible, like a random alphanumeric character
Letters should be a static const char array regardless though, so you're not potentially rebuilding it every call
Note that if you need to generate long pseudorandom strings of characters, this isn't a particularly efficient way to go about it since you're throwing away most of the random number you're generating each time, and using modulo division like this slightly overweights lower values, though it's probably not going to matter for what you're likely using this for
I would also recommend against using rand() if you have access to C++11 STL due to modulo bias (long story short, modulo is not always uniform) so using std::uniform_int_distribution might be better. an example:
It's not really overengineering replacing 1 fn with another. And I would argue if you want a random number, you want a RANDOM number. Overengineering would be saying the modulo operation introduces a bias and you need to use this beauty I have buried in my github
uint64_tSlotRng::Next(constuint64_tlower,constuint64_tupper){// manipulate rng to fit in range given
uint64_t res = lower +Next()/(UINT64_MAX /(upper - lower)+1);return res;}
Edit: if you're going to downvote I'd appreciate a reason, thanks
The principle is not language specific obviously but not every language offers a biased random function. I couldnt replicate the issue in neither C# nor Java for example. So the more apropriate question is which languages have a biased random function at all?
Not necessarily a power of two-- most random number generation functions have implementation-defined ranges, and you need to make sure that the range you're provided can be molded to your use case (e.g. by using RAND_MAX in C)
It's not about the language, it's how the maths work. But yes, most languages have a native method that does this better, I don't see how it would matter in which way the respective language is related to C, though.
Yeah obviously the maths stays the same no matter the language but the way a random number is implemented is not. And if a language inherits the random function from C, its affected directly aswell. Like Python...
rand() gives an unbiased number though, the bias is introduced by taking mod a number that doesn't factor into the original range size (i.e. a using modulus that isn't a power of 2). The bias isn't "inherited" from C because it wasn't part of the calculation that the library did in the first place, the bias is simply introduced by the calculation that you're writing explicitly.
You can make the int distribution based on the chars directly. Also random_device should only be used to initialize/seed a PRNG, not as the core RNG. It can be very taxing on the system
31
u/MurdoMaclachlan public boolean isInt(int i) { return true; } May 19 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
27
u/josanuz May 20 '23
Not bad, a couple of notes
randusingsrand()21
u/Badel2 May 19 '23
If this is C++ you shouldn't be using
rand(), but if you are a beginner then understandingstd::uniform_int_distributionmay be too hard.6
u/lestofante May 20 '23
you are in C++, so DO NOT USE C stuff like rand().
Not only because rand issue by itself (see later), but because C++ is a very different beast than C than come with better solution to many problems.
I suggest you to skim over "the C++ coding standard" when in doubt: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Also you are importing the namespace and not using it, so just dont. In general; the coding standard suggest to use it ONLY if you make heavy use of std stuff, and in your case where you mix C++ and C stuff, nameclash between C lib and std is very likely
This is a bad idea and screw up the random distribution, unless your modulo happen to be exactly modulo of RAND_MAX. In C++ use std::uniform_int_distribution
Rand() is considered harmful is a great talk that deep dive in the issue: https://www.youtube.com/watch?v=LDPMpc-ENqY
ok, but you notice you have an array of 27 but 26 letter, because the End of String; but if you change the array, maybe you add some accent or even lowercase latter, you have to remember to change 2 places in the code.
If you declare the array first, then you can use sizeof(letters) - 1 to obtain your modulo values, also i would drop the [27] and replace it with [], as now it all depends on sizeof.
If instead you want strict 26 letter, you should create a constepr value with it, and use it everywhere, and enable the warning (i think "pedantic") that will generate a warning if your initialization does not match the array declared size, and also -werror that make any warning into error is a very good idea for beginner.
9
u/Lez12345 May 19 '23
Not bad if you want to exclude letters like l and i, or like zero and O.
5
u/Pangocciolo May 20 '23
The only bad thing is "using namespace" statement. :)
2
u/MartonFerencziMoth May 20 '23
Why donโt you use the ascii encoding? Random generate a value in the range and parse to ascii char.
2
u/[deleted] May 20 '23
For a beginner the idea is more important than trying to shave a few bytes off the source code.
Does it work? If so then it's good to a point, the getting of the random number is another matter but that's best left to the spooks who love their RNG
Obviously it's only got a small spread of numbers as 64 chars is good enough for most people unless you are using a printer then it gets more fun but I was used to using a mainframe where one of the printers only needed 6 bits as it made the lines per minute a lot more so long as you didn't want lowercase which was fine for cobol listings for the Devs.
2
u/RoadRunnerChris May 20 '23
I wouldn't recommend this as it is not cryptographically secure (if randomness is of importance in this scenario.)
Here's what I'd do:
Here, we are using the
/dev/randomcharacter special device which is a cryptographically secure random byte generator.If you'd like, you can use
/dev/urandomif you care about a nonblocking application./dev/randomis only suitable for applications that need high quality randomness, and can afford indeterminate delays.The
/dev/randomdevice is a legacy interface which dates back to a time where the cryptographic primitives used in the implementation of/dev/urandomwere not widely trusted. Nowadays, it is common to choose/dev/urandomunless high quality absolute randomness is required./dev/randomwill return random bytes only within the estimated number of bits of fresh noise in the entropy pool, blocking if necessary (not returning any random bytes until fresh noise is available).1
u/valzargaming May 20 '23
I made something not quite unlike this a while ago, but a bit more complicated to allow for more customization.
$token = '';$length = 50;$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
while (strlen($token)<$length) $token .= $charset[(mt_rand(0,(strlen($charset)-1)))];
Keep in mind that the token created in my case is not and should not be used for security purposes, but merely a case of "Here's this thing I spit out that's somewhat unique and therefore unlikely to appear by happenchance, go put it somewhere and tell me when you did it so I can verify that it was actually you who did the thing."
1
u/purefan May 20 '23
Oh yes, the randomness rabbit hole... grab a torch, it goes deep
1
u/Cerulean_IsFancyBlue May 19 '23
Why 27? Itโs not being used as a string.
0
u/londocr May 20 '23
I'm not familiar with this language, I have a few questions
-13
u/Effective-Attorney33 May 19 '23 edited May 19 '23
Not horrible a couple pointers
using namespace stdis almost always a bad idea.Letters are pretty good here but you might be able to get away with a #define macro instead
Do something like at the top of the file
#define LETTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
And use that instead of your variable. You can think of a #define macro as a find and replace statement.
The preprocessor that runs before compilation will find and replace all cases of where LETTERS is used with
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
0
u/[deleted] May 19 '23
[deleted] โ view deleted comment