typeint=number;// For clarity (and brevity)constnumberFor=(x:int,y:int,layer:int):int=>{constbottomRight:int=layer**2,topRight:int=bottomRight+layer,distance:int=Math.abs(x-y);returntopRight+((y<=x)?-distance:distance);},numberAt(x:int,y:int):int=>{constdistance:int=2*Math.max(Math.abs(x),Math.abs(y));return(y>-x)?numberFor(x,y,distance-1):numberFor(-x,-y,distance);},printSpiral=(size:int):void=>{// Where `size` is the length of each sideconst// Figure out biggest possible number for spiral number spacingmaxNumSize:int=`${size**2}`.length,// Repeat that for all the numbers that will be printed each linelineFormat:string=newArray(size).fill(`%${maxNumSize}d`).join(' '),// Now figure out the actual bounds to usemax:int=(size/2)|0,// Shorthand for `Number.parseInt()`min:int=(size%2===0)?(-max+1):-max;// If running on node.js this can be circumvented by using non-console loggingletline:int[]=[];// Damn `console.log` for always printing a newline// It would be nice if JS had a range operator like python...for(lety=max;y>=min;y--){for(letx=min;x<=max;x++){line.push(numberAt(x,y));}console.log(lineFormat,...line);line=[];}};
I've tested the number spacing out to an 82x82 spiral, and assume that it would work further than that as well, but I was running out of horizontal screen space.
As I can see, you have written all the needed logic for a solution in O(1), but without node.js you need to assemble a line first, before printing it entirely. Something like this was my intention for allowing O(n).
Of course, your program consumes linear space, but I think the core concept can be regarded, like Alexey's, as O(1) solution.
I agree to your comment about ranges, by the way. Would you like to submit Python code?
In TypeScript:
I've tested the number spacing out to an 82x82 spiral, and assume that it would work further than that as well, but I was running out of horizontal screen space.
As I can see, you have written all the needed logic for a solution in O(1), but without node.js you need to assemble a line first, before printing it entirely. Something like this was my intention for allowing O(n).
Of course, your program consumes linear space, but I think the core concept can be regarded, like Alexey's, as O(1) solution.
I agree to your comment about ranges, by the way. Would you like to submit Python code?
I'd like to, but it's been a while since I last used Python and I've forgotten most of the rest of the nice syntax features.