While I don't think I have an efficient way of generating the spiral, I learnt a thing or two. My method is to rotate the grid by 90 degrees and take the top row from the grid and add it to the output.
(function(input) { input = input.flat(); function indexToXY(index, width) { let x = index % width; let y = Math.floor(index / width); return [x,y]; } function xyToIndex(x, y, width) { return (x + (y * width)); } function snail(grid, width, shrinkwidth) { if(grid.length == 0) { return []; } if(grid.length == 1) { return grid; } let part = grid.splice(0, width); width = Math.ceil(Math.sqrt(grid.length)); grid = grid.reduce((oup, item, index) => { let [x, y] = indexToXY(index, width); let pole = Math.floor(width/2); let polex = x - pole; let poley = y - pole; let r = Math.sqrt((polex*polex)+(poley*poley)); let fi = Math.atan2(poley, polex); fi -= Math.PI/2; let newx = Math.round((Math.cos(fi)*r)+pole); let newy = Math.round((Math.sin(fi)*r)+pole); let newIndex = xyToIndex(newx, newy, width); oup[newIndex] = item; return oup; }, []).filter(x=>x); if(shrinkwidth) { width--; } return part.concat(snail(grid, width, !shrinkwidth)); } return snail(input, Math.ceil(Math.sqrt(input.length)), true); })([[1,2,3,1], [4,5,6,4], [7,8,9,7], [7,8,9,7]])
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
While I don't think I have an efficient way of generating the spiral, I learnt a thing or two.
My method is to rotate the grid by 90 degrees and take the top row from the grid and add it to the output.