var garden = [], directions = input[0].split( /, /g); var line = 0, cell = 0; var match, regex = /{([#&!*])}/g; var path = ''; var rabbit = { "&" : 0, "*" : 0, "#" : 0, "!" : 0, "wall hits" : 0 }; for (var row in input) { if (row > 0) { var tokens = input[row].split( /, /g); garden.push(tokens); } } directions.forEach(function(direction) { if(changeCell(direction)) { var currCell = garden[line][cell]; while (match = regex.exec(currCell)) { rabbit[match[1]] += 1; } path += currCell.replace(/{([#&!*])}/g, '@') + '|'; } }); function changeCell(dir) { var tempCell = cell; var tempLine = line; switch (dir) { case 'right' : cell++; break; case 'down' : line++; break; case 'left' : cell--; break; case 'up' : line--; break; } if ((line < 0) || (line >= garden.length)) { rabbit['wall hits']++; line = tempLine; return false; } if ((cell < 0) || (cell >= garden[line].length)) { rabbit['wall hits']++; cell = tempCell; return false; } return true; } if (path !== '') { path = path.substring(0, path.length - 1); } else { path = 'no'; } console.log(JSON.stringify(rabbit) + '\n' + path);