takes a sentence and scrambles the words. how is this implemented? i
tried myself first with a for or while loop and tried if word is not
in new_sentence then new_sentence += word etc.
but that could go on for a long time and would be very slow for a
large text.
takes a sentence and scrambles the words. how is this implemented? i
tried myself first with a for or while loop and tried if word is not
in new_sentence then new_sentence += word etc.
but that could go on for a long time and would be very slow for a
large text.
I assume you already know how gets, split, and join work and the
question in your subject refers to sort_by. The sort_by method sorts the
enumerable (in this case, the array of words produced by split) using
the keys generated by the block. That is, sort_by calls the block once
for each element in the array. The block usually (but not in this case)
inspects the element and returns a key. You’re wanting a random sort, so
you use the rand method to return a random number as the key. The
sort_by method sorts the array in increasing order by the random
numbers. Since the keys are randomly generated, the array is randomly
ordered.
Is it deterministic? See my P.S. You can use srand to ensure that rand
returns the same sequence of numbers.
The doc for sort_by is pretty good. Try “ri sort_by”, and “ri
Kernel#rand”.
P.S. I’m sure there’s a lot of good things to be said about PRNGs and
stuff but I’ll let somebody else type it in.
P.S. I’m sure there’s a lot of good things to be said about PRNGs and
stuff but I’ll let somebody else type it in.
I’ll just add that Ruby’s rand is deterministic, but it uses a very good
PRNG algorithm (Mersenne twister). Unless you really need true
randomness, it’s good enough to use out-of-the-box.
P.S. I’m sure there’s a lot of good things to be said about PRNGs and
stuff but I’ll let somebody else type it in.
I’ll just add that Ruby’s rand is deterministic, but it uses a very good
PRNG algorithm (Mersenne twister). Unless you really need true
randomness, it’s good enough to use out-of-the-box.
Plus, opposed to other libs and languages, there is a random element in
seeding:
everyoen is missing my point. is the complete method deterministic?
not the rand…
What complete method? You presented two lines of code and in those the
only potential source of indeterminism is #rand (apart from the user
input), which is precisely why the discussion revolves around this.