I have an array rangers = ["red", "blue", "yellow", "pink", "black"]
(it's debatable that green should part of it, but I decided to omitted it)
I want to double the array elements so it returns rangers = ["red", "red", "blue", "blue", "yellow", "yellow", "pink", "pink", "black", "black"]
in that order.
I tried look around SO, but I could not find find a way to do it in that order. (rangers *= 2
won't work).
I have also tried rangers.map{|ar| ar * 2} #=> ["redred", "blueblue",...]
I tried rangers << rangers #=> ["red", "blue", "yellow", "pink", "black", [...]]
How can I duplicate elements to return the duplicate element value right next to it? Also, if possible, I would like to duplicate it n times, so when n = 3
, it returns ["red", "red", "red", "blue", "blue", "blue", ...]
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.
uniq is a Ruby method that returns a new array by removing duplicate elements or values of the array. The array is traversed in order and the first occurrence is kept.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
How about
rangers.zip(rangers).flatten
using Array#zip
and Array#flatten
?
A solution that might generalize a bit better for your second request might be:
rangers.flat_map { |ranger| [ranger] * 2 }
using Enumerable#flat_map
.
Here you can just replace the 2
with any value or variable.
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