chaoseverlasting
- 1,051
- 3
What exactly are hash functions and how do you use them to create a random string? What other ways are there to create random strings.
The discussion centers on the concept of hash functions and their role in generating random strings, as well as alternative methods for creating random strings. It includes technical explanations and practical coding examples, particularly in C++.
Participants generally agree on the distinction between hash functions and random string generation methods, but there is no consensus on the best approach to implement random string generation in C++.
Some limitations include the reliance on the randomness of the pseudo-random number generator and the assumptions made about the system time's effectiveness as a seed.
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
srand(time(0));
chaoseverlasting said:How would you get the system time in c++ and use it to create a random string?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(int argc, char *argv[])
{
if(argc < 2){
printf("USAGE: %s [Length of string]\n", argv[0]);
return 0;
}
int length = atoi(argv[1]);
char *randstr = malloc(length + 1);
randstr[length] = '\0';
time_t ltime = time(NULL);
srand(ltime);
int i;
for(i = 0; i < length; i++)
randstr[i] = (rand() % 26) + 65;
printf("%s\n", randstr);
return 0;
}
$ ./randstr
USAGE: ./randstr [Length of string]
$ ./randstr 20
MTZEKHHTQJGPDNHBNSTN
$ ./randstr 20
IEMBTDVFDEDMFWXEYESX
$ ./randstr 20
EMCYCCJOTCAJHCNHMQOH
$