iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 19
1

19 - RGB To Hex Conversion

Don't say so much, just coding...

Instruction

The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

The following are examples of expected output values:

  rgb(255, 255, 255) # returns FFFFFF
  rgb(255, 255, 300) # returns FFFFFF
  rgb(0,0,0) # returns 000000
  rgb(148, 0, 211) # returns 9400D3

Ruby

Init

  def rgb(r, g, b)
    # complete this function
  end

Sample Testing

  Test.assert_equals(rgb(0, 0, 0), '000000')
  Test.assert_equals(rgb(0, 0, -20), '000000')
  Test.assert_equals(rgb(300,255,255), 'FFFFFF')
  Test.assert_equals(rgb(173,255,47), 'ADFF2F')

Javascript

Init

  function rgb(r, g, b){
    // complete this function  
  }

Sample Testing

  Test.assertEquals(rgb(0, 0, 0), '000000')
  Test.assertEquals(rgb(0, 0, -20), '000000')
  Test.assertEquals(rgb(300,255,255), 'FFFFFF')
  Test.assertEquals(rgb(173,255,47), 'ADFF2F')

Thinking

想法(1): 不管傳進來的值 (r, g, b) 都先考慮當數字不在 0 ~ 255 時,需要給最大、小值
想法(2): 判斷完成後,再轉為 16 進位

https://ithelp.ithome.com.tw/upload/images/20201004/20120826ebtZaU8Oav.jpg
圖片來源:Unsplash Jonathan Kemper

Hint & Reference

Solution

Ruby

  # Solution 1
  def rgb(r, g, b)
    [r, g, b].map do |c|
      if c <= 0 
        "00"
      elsif c > 255
        "FF"
      else
        c.to_s(16).upcase    
      end
    end.join('')
  end
  
  # Solution 2
  def rgb(r, g, b)
    "%.2X" * 3 % [r, g, b].map{ |i| [[i, 255].min, 0].max }
  end
  
  # Solution 3
  def rgb(r, g, b)
    "%.2X" * 3 % [r, g, b].map{ |i| i.clamp(0, 255) }
  end

Javascript

  // Solution 1
  function rgb(r, g, b){
    return toHex(r) + toHex(g) + toHex(b);
  }
  
  function toHex(color) {
    if(color < 0)
      return "00";
    if(color > 255)
      return "FF";
    return ( "0" + (Number(color).toString(16)) )
                                 .slice(-2)
                                 .toUpperCase()
  }

上一篇
見習村18 - Maximum subarray sum
下一篇
見習村20 - Scramblies
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言