Skip to main content
6 of 12
edited body
Leaky Nun
  • 50.1k
  • 6
  • 110
  • 284

JavaScript, 247 237 bytes

n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=1*d.substring(1)
while(b--){
if(a=="N")y++
if(a=="S")y--
if(a=="E")x++
if(a=="W")x--
p=`(${x},${y})`
if(~e.indexOf(p))if(x==0&y==0)z++
else return 0
e+=p}}return x==0&y==0&z==0}

n is a function of input string s that returns 1 for true and 0 for false

Here's an ungolfed version for reference:

function n(s)
{
    var dir = s.match(/\w\d+/g);
    var x = y = z = 0;
    var been = "";
    for (d of dir)
    {
        var a = d[0];
        var b = 1*d.substring(1);
        while(b-- > 0)
        {
            if (a == "N") y++;
            if (a == "S") y--;
            if (a == "E") x++;
            if (a == "W") x--;
            var pt = "(" + x + "," + y + ")";
            if (~been.indexOf(pt))
                if (x==0 && y==0)
                    z++;
                else
                    return false;
            been += pt;
        }
    }
    return (x == 0 && y==0 && z == 0);
}

n=s=>{r=s.match(/\w\d+/g)
x=y=z=0
e=""
for(d of r){a=d[0]
b=1*d.substring(1)
while(b--){
if(a=="N")y++
if(a=="S")y--
if(a=="E")x++
if(a=="W")x--
p=`(${x},${y})`
if(~e.indexOf(p))if(x==0&y==0)z++
else return 0
e+=p}}return x==0&y==0&z==0}

console.log(n("N1E1S1W1"))
console.log(n("N1E1N1E1S2W2"))
console.log(n("N1S1E1W1"))
console.log(n("N4E2S2W4S2E2"))
console.log(n("N3E2S3"))

WaffleCohn
  • 311
  • 1
  • 7