How to get random 0 and 1 numbers

So basically for fun I tried to create a column of numbers (7 digits only 0 and 1) My code is 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 from 0s and 1s, all numbers are used.

+5
source share
5 answers

Here's the idiomatic Ruby:

5.times do
  puts (1..7).map { [0, 1].sample }.join
end

Let me unzip it:

5.times do...endpretty clear. Do something between doand endfive times.

(1..7) . , . map , . [0, 1].sample . sample, , 0, 1. .join . .join('-'), , (1-0-0-1-1-1-0-1). , (10011101).

.

, , . , Ruby Way. , " - ", , Ruby. , , . ", - , 7- ... 0s 1s... ". ( map ( )).

+12

, , :

someNumber = rand(1 << 7) # Seven digits, max; 1 << 7 is 10000000 in binary.

puts someNumber.to_s(2).ljust(7, '0') # 10110100, e.g.
+10

@minitech

 5.times { puts "%07b" % rand(128) }
+2

Ruby rand(), , .

(rand(2)) , . , .

- 0 127, . .

. , . , .

+1

, ( 1) :

def random_binary(length, n=1)
  raise ArgumentError if n < 1
  (1..n).map { "%0#{length}b" % rand(2**length) }
end

random_binary(7, 5)
#=> ["0011100", "1001010", "0101111", "0010101", "1100101"]
+1

All Articles