CodeWars: Snail Solution
Keep going in a wayApproach
Keep going in one direction at a time, with the order:
- right
- down
- left
- up
- ..then repeat
Implementation
1snail = function (array) {2 const n = array[0].length34 const visited = Array.from({ length: n }, _ => Array(n).fill(false))5 const res = []67 const valid = (row, col) => 0 <= row && row < n && 0 <= col && col < n8 const canGoUp = (row, col) => valid(row - 1, col) && !visited[row - 1][col]9 const canGoDown = (row, col) => valid(row + 1, col) && !visited[row + 1][col]10 const canGoLeft = (row, col) => valid(row, col - 1) && !visited[row][col - 1]11 const canGoRight = (row, col) => valid(row, col + 1) && !visited[row][col + 1]1213 const visit = (row, col) => {14 res.push(array[row][col])15 visited[row][col] = true16 }1718 for (let row = 0, col = 0; n > 0; ) {19 if (canGoRight(row, col)) {20 while (canGoRight(row, col)) visit(row, col++)21 continue22 }2324 if (canGoDown(row, col)) {25 while (canGoDown(row, col)) visit(row++, col)26 continue27 }2829 if (canGoLeft(row, col)) {30 while (canGoLeft(row, col)) visit(row, col--)31 continue32 }3334 if (canGoUp(row, col)) {35 while (canGoUp(row, col)) visit(row--, col)36 continue37 }3839 // final cell40 visit(row, col)4142 break43 }4445 return res46}
Comments
Loading comments...
Tags
codewars
array
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.