So basically for fun I was trying to generate a column of numbers (7 digits only 0s and 1s) My code's pretty short:
a = rand(0000000-1111111)
b = 220
a1 = rand(0000000-1111111)
a2 = rand(0000000-1111111)
a3 = rand(0000000-1111111)
a4 = rand(0000000-1111111)
a5 = rand(0000000-1111111)
while b !=0
puts a
puts a2
puts a3
puts a4
puts a5
end
My problem is that instead of generating a random column of 0s and 1s all the numbers are used.
Using the random.uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.
Definition and UsageThe random() method returns a random floating number between 0 and 1.
A random number generator always returns a value between 0 and 1, but never equal to one or the other.
The random module's rand() method returns a random float between 0 and 1.
Here's idiomaticish Ruby:
5.times do
puts (1..7).map { [0, 1].sample }.join
end
Let's unpack it:
5.times do...end
is pretty self-explanatory. Do whatever's between do
and end
five times.
(1..7)
generates an array with seven elements. We don't actually care what's in it right now. map
returns a new array where each element is the result of calling what's between the braces. So seven times we'll call [0, 1].sample
and squeeze the results into an array. The sample
itself, of course, randomly picks either 0
or 1
. Finally .join
turns an array into a string. If we'd said .join('-')
, for example, it'd put a hyphen between each element (1-0-0-1-1-1-0-1). But since we didn't specify anything it puts nothing between each element (10011101).
And there you have it.
As others have noted, for this particular problem it's possible to do faster and shorter things by using binary. I don't think this is the Ruby Way though. With respect to speed, "premature optimization is the root of all evil", and if you have a violent aversion to slow code you shouldn't be coding Ruby anyway. With regards to readability, that way may be shorter, but the above way is a lot clearer. "Oh, we're doing something five times, and that's going to be printing out a 7-thing long...random sequence of 0s and 1s...as a string". It almost reads like English (if you know the word map (definition three)).
The best way to solve this is probably to do base conversion:
someNumber = rand(1 << 7) # Seven digits, max; 1 << 7 is 10000000 in binary.
puts someNumber.to_s(2).ljust(7, '0') # 10110100, e.g.
Derivation of @minitech's answer
5.times { puts "%07b" % rand(128) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With