Choosing odd or even elements from an array

I was asked to write a piece of code that returns the odd elements of an array when the second argument, trueand even elements if it is false. So far I have written one half, and I need a method that can select odd elements.

def odds_and_evens(string, return_odds)
  if return_odds != false
    string.chars.to_a
  end
end

puts odds_and_evens("abcdefgh", true)
+4
source share
7 answers

If you add this code, you have 2 convenient methods for selecting odd or even values ​​from an array

class Array
  def odd_values
    values_at(* each_index.select(&:odd?))
  end
  def even_values
    values_at(* each_index.select(&:even?))
  end
end
+10
source
class Array
  def odd_values
    e = [false, true].cycle
    select { e.next }
  end
  def even_values
    e = [true, false].cycle 
    select { e.next }
  end
end

arr = "Here is a simple illustration of these methods".split

arr.odd_values
  #=> ["is", "simple", "of", "methods"]
arr.even_values
  #=> ["Here", "a", "illustration", "these"]
+3
source

Range#step:

def odds_and_evens(string, return_odds)
  start = return_odds ? 1: 0
  (start...string.size).step(2).map { |i| string[i] }
  # OR  string.chars.values_at(*(start...string.size).step(2))
end

odds_and_evens("abcdefgh", true) # => ["b", "d", "f", "h"]
odds_and_evens("abcdefgh", false) # => ["a", "c", "e", "g"]
+1
def odds_and_evens(string, return_odds)
  string.chars.select.with_index{|_, i| return_odds ? i.odd? : i.even?}
end

odds_and_evens("abcdefgh", true)  # => ["b", "d", "f", "h"]
odds_and_evens("abcdefgh", false) # => ["a", "c", "e", "g"]
+1

, - , - "", :

def odds_and_evens(string, return_odds)
  new_string = string.chars.to_a
  even_odd_string = []

  new_string.each_with_index do |letter, index|
    if return_odds != true && index %2 == 0
      even_odd_string << letter
    elsif return_odds != false && index %2 == 1
      even_odd_string << letter
    end
  end
  even_odd_string
end

puts odds_and_evens("abcdefgh", true)
+1

:

def odds_and_evens(string, return_odds)
  string.chars.each_slice(2).collect {|pair| return_odds ? pair.last : pair.first }
end

p odds_and_evens("abcdefgh", false)
#=> ["a", "c", "e", "g"]
p odds_and_evens("abcdefgh", true)
#=> ["b", "d", "f", "h"]

:

def odds_and_evens(string, return_odds)
  indices = (0...string.size).select {|i| return_odds ? i.odd? : i.even? }
  string.chars.values_at(*indices)
end
0
source

The accepted answer is ok but slow.

It is 2-3 times faster. In addition, it does not change the size of the Array, so it can be used for other objects, for example, ActiveRecod :: Relation

def self.even_elements(list)
    list.values_at(*0.step(list.size - 1, 2))
end

def self.odd_elements(list)
    list.values_at(*1.step(list.size - 1, 2))
end
0
source

Source: https://habr.com/ru/post/1620139/


All Articles