How to shuffle the first n elements in array

  • A+
Category:Languages

Let:

example = [1,2,3,4,5,6,7,8,9] 

I want to shuffle its first five elements. Other elements have to remain under the same index, e.g.:

[2,4,1,3,5,6,7,8,9] [3,1,4,5,2,6,7,8,9] # etc 

I've tried example.shuffle, but it shuffles all elements.

 


You can get the first 5 elements via []:

example[0, 5] #=> [1, 2, 3, 4, 5] 

Likewise, you can set the first 5 element via []=:

example[0, 5] = [5, 4, 3, 2, 1] #=> [5, 4, 3, 2, 1]  example #=> [5, 4, 3, 2, 1, 6, 7, 8, 9] 

So to shuffle the first 5 elements, you could use:

example[0, 5] = example[0, 5].shuffle #=> [3, 2, 1, 4, 5]  example #=> [3, 2, 1, 4, 5, 6, 7, 8, 9] 

Note that example[0, 5].shuffle! would not work because Array#[] returns a new array instead of a reference to a subarray (there's no such thing in Ruby).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: