I wondered if there was a more compact method of generating things like
a random string, or a random list of numbers than I'm using now (using
ruby 1.9.0-1)
I wondered if there was a more compact method of generating things like
a random string, or a random list of numbers than I'm using now (using
ruby 1.9.0-1)
Datum: Mon, 26 May 2008 17:45:57 +0900
Von: Boris Schmid <boris@bagofsouls.com>
An: ruby-talk@ruby-lang.org
Betreff: briefest method of generating a list of random numbers?
Hi all,
I wondered if there was a more compact method of generating things like
a random string, or a random list of numbers than I'm using now (using
ruby 1.9.0-1)
I wondered if there was a more compact method of generating things like
a random string, or a random list of numbers than I'm using now (using
ruby 1.9.0-1)
("a".."z").sort_by {rand}.join
this is not really the same, maybe
(("a".."z").to_a * N).sort_by { rand }[0..x].join
does what OP wants (if N is large enough) and although this approach
has a certain elegance it would be very,very inefficent.
Cheers
R.
···
On Mon, May 26, 2008 at 12:39 PM, S2 <non.sto.gioando@nien.te> wrote:
For strings I'll have to use the one above, but arrays now read a bit
more natural (to my eyes). The size doesn't matter that much, but it is
simpler to understand.
population = Array.new(POP_SIZE) {
function_that_generates_a_random_individual }
vs the old
population = ; POP_SIZE.times {population <<
function_that_generates_a_random_individual }
Array(arg) creates an array equal to 'arg' (if it responds to .to_ary)
or an array containing precisly 'arg' otherwise. It never yields.
There is also
(1..100).map { rand }
And for strings
(1..100).map { (rand(26)+97).chr }.join
Lars
···
On May 26, 11:16 am, Mikael Høilund <mik...@hoilund.org> wrote:
On May 26, 2008, at 10:45, Boris Schmid wrote:
> Hi all,
> I wondered if there was a more compact method of generating things
> like
> a random string, or a random list of numbers than I'm using now (using
> ruby 1.9.0-1)
Duh. I can just use the Array.new, and append a .join at the end to get
the random string. And Axel, I'm generating quite a lot of arrays in my
small prog, and using this shorter way makes it indeed clearer :). It is
definitly worth it.
For strings I'll have to use the one above, but arrays now read a bit
more natural (to my eyes). The size doesn't matter that much, but it is
simpler to understand.
Pack seems to be faster than the combination of .chr and join, which is
a nice side-effect, as I'm running simulations in ruby, and they takes
aeons of time (well, nearly a week). Don't ask me why I'm using ruby, it
just sort of happened ;), and the code is only 160 lines, which compares
favorably to the C ancestor of this simulation (which did more or less
the same in 4000 lines)