Advertisement
Guest User

Rabit

a guest
Apr 6th, 2015
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var garden = [], directions = input[0].split( /, /g);
  2.     var line = 0, cell = 0;
  3.     var match, regex = /{([#&!*])}/g;
  4.     var path = '';
  5.  
  6.     var rabbit = {
  7.         "&" : 0,
  8.         "*" : 0,
  9.         "#" : 0,
  10.         "!" : 0,
  11.         "wall hits" : 0
  12.     };
  13.  
  14.     for (var row in input) {
  15.         if (row > 0) {
  16.             var tokens = input[row].split( /, /g);
  17.             garden.push(tokens);
  18.         }
  19.     }
  20.  
  21.     directions.forEach(function(direction) {
  22.         if(changeCell(direction)) {
  23.             var currCell = garden[line][cell];
  24.             while (match = regex.exec(currCell)) {
  25.                 rabbit[match[1]] += 1;
  26.             }
  27.  
  28.             path += currCell.replace(/{([#&!*])}/g, '@') + '|';
  29.         }
  30.     });
  31.  
  32.     function changeCell(dir) {
  33.         var tempCell = cell;
  34.         var tempLine = line;
  35.        
  36.         switch (dir) {
  37.             case 'right' : cell++; break;
  38.             case 'down' : line++; break;
  39.             case 'left' : cell--; break;
  40.             case 'up' : line--; break;
  41.         }
  42.  
  43.         if ((line < 0) || (line >= garden.length)) {
  44.             rabbit['wall hits']++;
  45.             line = tempLine;
  46.  
  47.             return false;
  48.         }
  49.  
  50.         if ((cell < 0) || (cell >= garden[line].length)) {
  51.             rabbit['wall hits']++;
  52.             cell = tempCell;
  53.            
  54.             return false;
  55.         }
  56.  
  57.         return true;
  58.     }
  59.  
  60.     if (path !== '') {
  61.         path = path.substring(0, path.length - 1);
  62.     } else {
  63.         path = 'no';
  64.     }
  65.  
  66.     console.log(JSON.stringify(rabbit) + '\n' + path);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement