iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
1

25 - Range Extraction

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

Instruction

A format for expressing an ordered list of integers is to use a comma separated list of either

  • individual integers
  • or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")

Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

Example:

  solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
  # returns "-6,-3-1,3-5,7-11,14,15,17-20"
``  

### Ruby

#### Init

```ruby
  def solution(list)
    #todo: complete solution
  end

Sample Testing

  Test.assert_equals(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]), "-6,-3-1,3-5,7-11,14,15,17-20")

Javascript

Init

  function solution(list){
   //TODO: complete solution 
  }

Sample Testing

  Test.assertEquals(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]), "-6,-3-1,3-5,7-11,14,15,17-20")

Thinking

想法(1): 如果現在的數 +1 跟下一位數相等,就會被算在同個區間
想法(2): 如果只有一位數的話回傳該數,一位到兩位數之間回傳該兩位數,超過則回傳區間並且加上符號 -

https://ithelp.ithome.com.tw/upload/images/20201010/201208261dOJS0P7LB.jpg
圖片來源:Unsplash Sincerely Media

Hint & Reference

Solution

Ruby

  # Solution 1
  def solution(list)
    list.chunk_while { |i, j| i + 1 == j }
        .flat_map { |a|
          if a.size == 1
            a.first.to_s
          elsif a.size == 2 
            [a.first.to_s, a.last.to_s]
          else
            "#{a.first}-#{a.last}"
          end
        }
        .join(',')
  end

Javascript

  // Solution 1
  function solution(list){
     for(var i = 0; i < list.length; i++){
        var j = i;
        while(list[j] - list[j + 1] == -1) j++;
        if(j != i && j-i > 1) list.splice(i, j - i+1, list[i] + '-' + list[j]);
    }
    return list.join();
  }

上一篇
見習村24 - Best travel
下一篇
見習村26 - Tongues
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言