iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 2
1

02 - Unique In Order

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

Instruction

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

  uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
  uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
  uniqueInOrder([1,2,2,3,3])       == [1,2,3]

Ruby

Init

  def unique_in_order(iterable)
    # put your solution here
  end

Sample Testing

  Test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])

Javascript

Init

  var uniqueInOrder = function(iterable){
    // your code here - remember iterable can be a string or an array
  }

Sample Testing

  Test.assertSimilar(uniqueInOrder('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])

Thinking

想法(1): 從舉例可以看出會傳入的 iterable 的型態會是陣列、字串,所以需先判斷型態,否則後面能接的方法會有不能用的情況
想法(2): 分群的概念,如果後面的英文字跟前一個相同的話,只顯示一個
想法(3): 可以用空陣列塞值進去、或者是分群 selectuniq 的那個值

https://ithelp.ithome.com.tw/upload/images/20200917/20120826A5q7a8riTw.jpg
圖片來源:Unsplash Roman Bozhko

Hint & Reference

Solution

Ruby

  # Solution 1
  def unique_in_order(iterable)
    (iterable.is_a?(String) ? iterable.split('') : iterable)
      .chunk{ |s| s }
      .map(&:first)
  end
  
  # Solution 2
  def unique_in_order(iterable)
    (iterable.is_a?(String) ? iterable.chars : iterable)
      .chunk { |s| s }
      .map(&:first)
  end
  
  # Solution 3
  def unique_in_order(iterable)
    iterable.is_a?(String) ? iterable.squeeze.split('') : iterable.uniq
  end

Javascript

  // Solution 1
  var uniqueInOrder = function(iterable){
    var result = [];
    for(i = 0; i < iterable.length; i++) {
      if (iterable[i] != iterable[i+1]) result.push(iterable[i]);
    }
    return result;
  }
  
  // Solution 2
  var uniqueInOrder = function(iterable){
    return [...iterable].filter((i, index) => i !== iterable[index-1])
  }

上一篇
見習村01 - Multiples of 3 or 5
下一篇
見習村03 - Highest Scoring Word
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言