Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random mask array?

Tags:

arrays

ruby

I've an array with 128 values, each value is 1:

length = 128
partials = Array.new length

partials.each_index do |i|
    partials[i] = 1
end

I want to set value 0 on some (random) position (for example, on pos 1,6,50,70,100,112,120).

Of course, the number of position could be different every time, and if I choose 7 different position, I want to end with 7 different pos changed.

What's the faster way to do this in Ruby?

like image 732
markzzz Avatar asked Jul 29 '26 01:07

markzzz


1 Answers

Assuming you want to have n elements with value 0, you can do the below:

n = 5
partials[0,n] = [0]*n
partials.shuffle

Alternatively, can also be written as:

partials.tap{|p| p[0,n] = [0]*n}.shuffle
like image 138
Wand Maker Avatar answered Jul 31 '26 05:07

Wand Maker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!