[Solved] Sort (hex) colors by Hue [closed]


In this updated example also we don’t care about hash, we’ll just deal with an arrays of hex colors:

require 'paint'

#intantiate web_colors from gist and shuffle them
eval(`curl https://gist.githubusercontent.com/lacostenycoder/394341d3c63589a050d72b8d9ae529aa/raw/4a11cd6ca81e07a643e5f3481e38494ff3c9b973/web_colors_shuffle.rb`)

def hex_to_rgb(hex)
  h = hex.gsub("#","")
  /(?<r>..)(?<g>..)(?<b>..)/ =~ h
  [r,g,b].map {|cs| cs.to_i(16)}
end

def rgb_to_hsl(r,g,b, by_hue=false)
  # normalize r, g and b
  r /= 255.0
  g /= 255.0
  b /= 255.0

  c_min = [r,g,b].min
  c_max = [r,g,b].max

  h = s = l = (c_min + c_max) / 2

  d = (c_max - c_min)#.to_f

  # compute hue
  if c_max == c_min
    h = s = 0.0 # achromatic i.e. ffffff or 000000
  else
    s = l > 0.5 ? d / (2 - c_max - c_min) : d / (c_max + c_min);
    h = (g - b) / d + ( g < b ? 6 : 0) if c_max == r
    h = (b - r) / d + 2 if c_max == g if c_max == g
    h = (r - g) / d + 4 if c_max == b if c_max == b
  end
  h /= 6
  by_hue ? h : [h, s, l]
end

def sort_em(colors, by_hue=false)
  colors.sort_by { |color| rgb_to_hsl(*hex_to_rgb(color), by_hue) }
end

def puts_em(colors)
  colors.each{|color| puts Paint[color, color]}
end

#shuffled web_colors sorted by hue
puts "\nShuffled web_colors by hue \n\n"
puts_em(sort_em @shuffled, by_hue=true)

puts "Shuffled web_colors by HSL \n\n"
#shuffled web_colors sorted by HLS
puts_em(@shuffled)

# sample uniformly at random from RGB space
colors = 200.times.map {  (0..255).to_a.sample(3).map { |i| i.to_s(16).rjust(2, '0')}.join   }

puts "\n Shuffled Random By Hue\n\n"
puts_em(sort_em colors, by_hue=true)

puts "\nShuffled Random by HSL\n\n"
puts_em(sort_em colors)

You may need to first run gem install paint and you can download gist of this

17

solved Sort (hex) colors by Hue [closed]