DEV Community

Discussion on: Challenge - Print Spiral

Collapse
 
prodigalknight profile image
RevanProdigalKnight

In TypeScript:

type int = number; // For clarity (and brevity)

const
  numberFor = (x: int, y: int, layer: int): int => {
    const
      bottomRight: int = layer ** 2,
      topRight: int = bottomRight + layer,
      distance: int = Math.abs(x - y);

    return topRight + ((y <= x) ? -distance : distance);
  },
  numberAt(x: int, y: int): int => {
    const distance: 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 side
    const
      // Figure out biggest possible number for spiral number spacing
      maxNumSize: int = `${size ** 2}`.length,
      // Repeat that for all the numbers that will be printed each line
      lineFormat: string = new Array(size).fill(`%${maxNumSize}d`).join(' '),
      // Now figure out the actual bounds to use
      max: 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 logging
    let line: int[] = []; // Damn `console.log` for always printing a newline

    // It would be nice if JS had a range operator like python...
    for (let y = max; y >= min; y--) {
      for (let x = 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.

Collapse
 
heikodudzus profile image
Heiko Dudzus • Edited

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?

Collapse
 
prodigalknight profile image
RevanProdigalKnight

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.