Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate array elements in Ruby

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", ...]

like image 563
Iggy Avatar asked Jul 25 '16 18:07

Iggy


People also ask

How do you duplicate elements in an array?

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.

How do you check if there are duplicates in an array Ruby?

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.

What does .uniq do in Ruby?

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.

What does .select do in Ruby?

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.


1 Answers

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.

like image 131
Julian Kniephoff Avatar answered Sep 19 '22 17:09

Julian Kniephoff