R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

Spiral Jetty

The Question

Write a function that will generate a spiral

of the form below:

resultArray = [[0,0],[1,0],[1,1],[0,1],[-1,1],[-1,0],...,[-2,-1],[-2,-2]]

        var spiral = function(n){

            var direction;
            x=0;
            y=0;
            resultArray = [[0,0]]
            for (var k=1; k < n; k++){
                direction = k%2;
                if (direction === 1){
                   // Move to the right then move up
                }
                if (direction === 0){
                   // Move to the left then move down
                }
            }
            return resultArray;
        }

k = 1 : [[0,0],[1,0],[1,1]]

k = 2 : [[0,0],[1,0],[1,1],                                         ]

[0,1],[-1,1],[-1,0],[-1,-1]

k=1

k=1

             k=2            

k=2

|

|

|

|

|

|

|

Approach

- for each k, you take 

k steps in both the x

and y direction

- alternate between

+ and - direction

            for (var k=1; k < n; k++){
                direction = k%2;
                if (direction === 1){
                    var i = 0;
                    var j = 0;
                    while(i < k){
                        x++;
                        resultArray.push([x,y]);
                        i++
                    }
                    while(j < k){
                        y++;
                        resultArray.push([x,y])
                        j++
                    }
                }
                if (direction === 0){
                    var i = 0;
                    var j = 0;
                    while (i < k){
                        x--;
                        resultArray.push([x,y]);
                        i++;
                    }
                    while (j < k){
                        y--;
                        resultArray.push([x,y]);
                        j++
                    }
                }
            }

- x and y represent

the coordinates

- i and j control the

number of steps taken

i = 0

i = 0

i = 1

j = 0

j = 0

j = 1

i = 1

i = 0

i = 2

Approach

Full Solution

Made with Slides.com