DEV Community

Discussion on: Daily Challenge #59 - Snail Sort

Collapse
 
chrisachard profile image
Chris Achard

Tricky! Not sure I found the most efficient way to do it - but it works, and I think it's relatively clean(ish) :)

Watch me solve it too: youtu.be/h-OzkY1_8mU

const snail = array => {
  const middle = array.slice(1, array.length - 1).map(row => 
    row.slice(1, row.length - 1)  
  )

  return [
    array[0],
    array.slice(1, array.length - 1).map(row => 
      row[row.length - 1]
    ),
    array.length > 1 ? array[array.length - 1].reverse() : [],
    array.slice(1, array.length - 1).reverse().map(row => 
      row[0]
    ),
    middle.length > 0 ? snail(middle) : []
  ].flat()
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
antuonettte profile image
Antonio Turner

Hey Chris, I made a replica of your solution translated to Python3.5 or greater.

from itertools import chain

def snail(arr):
    mid = list(map(lambda row : row[slice(1, len(row)-1)], arr[slice(1,len(arr)-1)]))


    return list(chain.from_iterable([
        arr[0],
        list(map(lambda row: row[len(row)-1], arr[slice(1,len(arr)-1)])),
        list(reversed(arr[len(arr)-1])) if len(arr) > 1 else [],
        list(map(lambda row: row[0],list(reversed(arr[slice(1,len(arr)-1)])))),
        snail(mid) if len(mid) > 0 else []

     ]))if len(arr) >= 1 else [[]]

Enter fullscreen mode Exit fullscreen mode