iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 21

見習村21 - Snail

21 - Snail

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

Instruction

Snail Sort

Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

  array = [[1,2,3],
           [4,5,6],
           [7,8,9]]
  snail(array) #=> [1,2,3,6,9,8,7,4,5]

For better understanding, please follow the numbers of the next array consecutively:

  array = [[1,2,3],
           [8,9,4],
           [7,6,5]]
  snail(array) #=> [1,2,3,4,5,6,7,8,9]

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].

Ruby

Init

  def snail(array)
    # enjoy
  end

Sample Testing

  def test input , expected
    output = snail(input)
    Test.expect(expected == output, "When snail(#{input}) expected #{expected} but got #{output}")
  end
  
  test( [[1,2,3],[4,5,6],[7,8,9]] , [1, 2, 3, 6, 9, 8, 7, 4, 5])

Javascript

Init

  snail = function(array) {
    // enjoy
  }

Sample Testing

  Test.assertDeepEquals(snail([[]]), []);
  Test.assertDeepEquals(snail([[1]]), [1]);
  Test.assertDeepEquals(snail([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5]);
  Test.assertDeepEquals(snail([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]), [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13]);
  Test.assertDeepEquals(snail([[1, 2, 3, 4, 5, 6], [20, 21, 22, 23, 24, 7], [19, 32, 33, 34, 25, 8], [18, 31, 36, 35, 26, 9], [17, 30, 29, 28, 27, 10], [16, 15, 14, 13, 12, 11]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]);

Thinking

想法(1): 需要花時間找一下規律,每次將陣列取第一個的時候,後面剩餘的陣列必須還有些動作來轉換
想法(2): 轉換直至陣列為空為止,可以透過遞迴或者是 while 迴圈來寫

https://ithelp.ithome.com.tw/upload/images/20201006/20120826BoD8viU9wc.jpg
圖片來源:Unsplash Dagny Reese

Hint & Reference

Solution

Ruby

  # Solution 1
  def snail(array)
    result = []
    while array.flatten.any?
      result << array.shift
      array = array.transpose.reverse
    end
    result.flatten
  end
  
  # Solution 2
  def snail(array)
    array.empty? ? [] : array.shift + snail(array.transpose.reverse)
  end

Javascript

  // Solution 1
  function snail(array) {
    var vector = [];
    while (array.length) {
      vector.push(...array.shift());
      array.map(row => vector.push(row.pop()));
      array.reverse().map(row => row.reverse());
    }
    return vector;
  }

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

尚未有邦友留言

立即登入留言