1

Let's say I have a string main_string = "germany"

And now I want to generate random strings that contain this main_string

The results should be for example:

 germanyXv43
 Fggermany3s
 germany55FR

Whats the best way to do this?

I thought in using SecureRandom

For example:

30000.times do 
   "germany" + SecureRandom.hex(3)
end 

But as you can guess then germany would be always at the beginning of the string:

germany8s5
germanyDF4
......

How can I do it more Random? Thanks!

3
  • Generate a random number representing the character after which to insert it? Also I'm not sure what your giant loop is for. Commented Apr 13, 2015 at 14:49
  • SecureRandom.hex(3) + "germany" + SecureRandom.hex(3) i guess) Commented Apr 13, 2015 at 14:49
  • @Ix00st it shouldn't be always in the middle, sometimes it should be at the front then at the end or somewhere in the middle! Thankns for your help! Commented Apr 13, 2015 at 14:53

1 Answer 1

6

Create an Array and shuffle it:

(["germany"] + SecureRandom.hex(3).chars).shuffle.join
# => "cgermany06f96"
# => "70efgermanyb4"
# => "germany934732"
# => "ebgermany9e4f"
Sign up to request clarification or add additional context in comments.

4 Comments

Thats exactly what i was searching for!
BTW in your example you are using SecureRandom.hex(3) to generate random string of length 3. That is incorrect. The length of the result string is twice of n.
Thanks for that info! How many posibilites has a String generated with SecureRandom.hex(3). Im thinking of 16 * 16 * 16 is that correct?
I guess you can calculate combinations with allowed repetition using formula: (n+r-1)! / r!(n-1)! that makes total 54264 for n=16 and r=6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.