Thread: Possible algorithms for random strings in C++

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    8

    Possible algorithms for random strings in C++

    Hello all!
    It's Tech2011 again!
    I have another stupid question to throw out there for you all!
    I am looking for an algorithm I could use in C++ to develop random strings of both alphabetical letters, ASCII symbols, and integers.
    I have developed an algorithm that does this sort of thing, but not quite random...only partially random. Here's what I've developed:

    srand((unsigned)time(0));
    int bit=rand() % 9 + 1;
    cout << "Random string: ";
    switch (bit){
    case 1:
    cout << "S" << rand() % 99999 << "/" << rand() % 999999 <<"A~D" << "\n" ;
    break;
    case 2:
    cout << "PoP" << rand() % 99999 << "7(Y" << rand() % 99999 << "\n" ;
    break;
    case 3:
    cout << rand() % 99999 << "Tk-i" << rand() % 99999<< "\n" ;
    break;
    case 4:
    cout << "&" << rand() % 99999 << "V" << rand() % 99999 <<"#W"<<"\n" ;
    break;
    case 5:
    cout << "@R" << rand() % 99999 << rand() % 99999 <<"yK"<< "\n" ;
    break;
    case 6:
    cout << rand() % 99999 << "PhP/d" << rand() % 99999<< "\n" ;
    break;
    case 7:
    cout << rand() % 99999 <<"J" << rand() % 99999 <<"Fl"<< "\n" ;
    break;
    case 8:
    cout << rand() % 99999 << ";" << rand() % 99999 <<"W!-]" << "\n" ;
    break;
    case 9:
    cout << "*Q" << rand() % 99999 << "mR=" << rand() % 99999 << "\n" ;
    break;
    default:
    cout << "String could not be generated because the default switch was reached." <<bit;
    break;

    Of course, there are multiple problems with this. For one thing, the majority, or at least a good portion of the "random" string is predictable and is reproducible. So it really isn't random, since the rand() function I've used, even with the time seeded into the algorithm, is still predictable. It's obvious that I could just change the letters and symbols inputted in the switch statement every so often, but that would not be efficient and would only be partially random and would eventually become reproducible. And, I know that I could/should add more switch statements with more random letters and symbols, but again, one of my goals is efficiency, alongside randomness. I understand that C++ rand() function was not designed to generate really good randomness, but I should at least be able to generate better randomness than what is provided in the algorithm I've developed.
    Any and all suggestions to improve this algorithm, or a new algorithm, are welcome and appreciated!
    Thanks again and sorry if this seems like a stupid question!
    Tech2011

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well you could post your code with the all-important braces in place, rather than ripping them all out so you don't have to deal with the code tags issue.

    You know, it's there for a reason - to make code readable.

    [code]
    Code:
    int main ( ) {
      // your code here, nicely indented
      return 0;
    }
    [/code]
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User gardhr's Avatar
    Join Date
    Apr 2011
    Posts
    151
    Here's a start:

    Code:
    #include <string>
    #include <cstdlib>
    #include <ctime>
    
    class random_text_generator
    {
    	public:
    	random_text_generator(const std::string& str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    	: m_str(str)
    	{
    		std::srand(std::time(0));
    	}	
    	std::string operator ()(std::size_t len = 1)
    	{
    		std::string seq;
    		std::size_t siz = m_str.size();
    		if(siz)
    			while(len--)
    				seq.push_back(m_str[rand() % siz]);
    		return seq;
    	}
    	private:		
    	std::string m_str;
    };
    
    #include <iostream>
    
    int main(void)
    {
    	using namespace std;
    	random_text_generator rtg;
    	for(size_t cnt = 0; cnt < 16; ++cnt)
    	{
    		cout << rtg(cnt) << endl;
    	}
    }

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    How does showing a possible solution help the OP in any way? Stop handing out answers and let people think for themselves.

  5. #5
    Registered User gardhr's Avatar
    Join Date
    Apr 2011
    Posts
    151
    Quote Originally Posted by VirtualAce View Post
    How does showing a possible solution help the OP in any way?
    Providing a straight-forward, concrete example is sometimes the best approach, especially when someone seems quite far from understanding a given problem. Notice that the OP was not whining for help, and moreover that my response was not exactly a solution to his particular problem. It was just a helpful nudge in the right direction.

  6. #6
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    @gardhr, you forgot to put "return 0;" at the end of main!
    Devoted my life to programming...

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by Sipher View Post
    @gardhr, you forgot to put "return 0;" at the end of main!
    Ah, this is a style point in C++; the language allows for an implicit return. See Stroustrup FAQ-2
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Yeah, so I see. But I prefer it to be there.
    Devoted my life to programming...

  9. #9
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by Sipher View Post
    Yeah, so I see. But I prefer it to be there.
    As do I, my friend.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by gardhr View Post
    Providing a straight-forward, concrete example is sometimes the best approach, especially when someone seems quite far from understanding a given problem. Notice that the OP was not whining for help, and moreover that my response was not exactly a solution to his particular problem. It was just a helpful nudge in the right direction.
    And you have to know that he just did the scoop and poop, dropping it directly into his own code, then automatically turned off his brain so that he doesn't have to waste any more time thinking about stupid things like *his homework*.

  11. #11
    Registered User gardhr's Avatar
    Join Date
    Apr 2011
    Posts
    151
    Quote Originally Posted by CommonTater View Post
    And you have to know that he just did the scoop and poop, dropping it directly into his own code, then automatically turned off his brain so that he doesn't have to waste any more time thinking about stupid things like *his homework*.
    Or maybe it stimulated a creative thought process? Teaching isn't all about forcing people to figure everything out on their own. Demonstrating practical techniques helps to hone problem-solving skills, and tends to reinvigorate interest as well.

    My impression of the OP was that he was earnestly seeking some guidance, so I chose to post a working example. That's all.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by CommonTater View Post
    And you have to know that he just did the scoop and poop, dropping it directly into his own code, then automatically turned off his brain so that he doesn't have to waste any more time thinking about stupid things like *his homework*.
    As much as I don't like solution dumping either, we don't know this is homework. I get the impression that it isn't, but if it is then clearly nobody is going to believe that he wrote that anyway, and for most assignments we see here they are not allowed to use the SC++L. Having a look at the other thread the OP started, he seems like an honest person, using his real name and all.
    If it had been preceeded by an explanation of a how one could go about designing such a thing, then I think it would be fine.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Umm, guys, I don't think any of us answered the OP's question. ( I know I didn't! )

    He asked for a better random numbers algorithm, one which isn't predictable.

    I suggest doing a little search on the web about RNG ( Random Number Generator ) and PRNG ( Pseudo RNG ) for details. Wikipedia was some good articles!
    Devoted my life to programming...

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I have developed an algorithm that does this sort of thing, but not quite random...only partially random. Here's what I've developed:

    And is this line
    srand((unsigned)time(0));

    In the same kind of loop or function being used to call rand() ?


    Well it shouldn't be.

    Put
    srand((unsigned)time(0));
    right at the start of main(), and make sure it's only done ONCE!

    The standard rand() is good enough for any likely homework scenario - if used correctly.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random exclamation point at end of strings
    By -world in forum C Programming
    Replies: 8
    Last Post: 07-09-2010, 11:37 PM
  2. Get 5 random strings containing names
    By kevingarnett in forum C Programming
    Replies: 5
    Last Post: 03-17-2010, 11:42 AM
  3. random strings?
    By Bobit in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 02:18 AM
  4. any more algorithms ?
    By black in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 07-31-2002, 01:00 AM
  5. C Algorithms
    By Garfield in forum C Programming
    Replies: 2
    Last Post: 09-28-2001, 02:59 AM

Tags for this Thread