loading...

re: Daily Challenge #220 - What Dominates Your Array? VIEW POST

FULL DISCUSSION
 

The edge cases made this one tricky. Here's a working function in Ruby without using Tally

def dominator(arr)
  baseline = arr.length / 2

  # Tally how many times each `n` is in the array
  # Sort by value
  # Delete any entries where the value is less than or equal to the baseline (half the length of the array)
  # Put values in order, largest to smallest
  # Turn it back into a hash

  result = arr.inject(Hash.new(0)) { |memo, item| 
    memo[item] += 1; 
    memo
  }.sort_by{|key,value| value}.delete_if {|key, value| value <= baseline }.reverse.to_h

  result != {} ? result.values.first : -1

end

Results

dominator([3,4,3,2,3,1,3,3]) #> 5
dominator([1,1,1,2,2,2]) #> -1
dominator([1,1,1,2,2,2,2]) #> 4
code of conduct - report abuse