Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a rectangular field of size NxM, filled with numbers and directions.
- On each cell on the field there will be a direction marked with the letters l, r, u, d.
- On the first row the values are from 1 to M, on the second row β from M+1 to 2*M, on the third row β
- from 2*M +1 to 3*M, on the Nth row β from (N-1)*M to N*M. By given start position, find the path outside
- of the field, or print if you are lost. The method Solve accepts a zero-based array of strings.
- The arguments are as follows: args[0] contains M and N separated by a single space (" "); args[1] contains R and C β
- the start position (the star position is zero-based); args[2] to args[N+2] contain exactly M characters
- (only the letters 'l', 'r', 'u' or 'd'). The output should contain a single string. */
- "use strict";
- function solve(args) {
- var dimensions = args[0].split(/\s/).filter(Boolean);
- var rows = parseInt(dimensions[0]), cols = parseInt(dimensions[1]);
- var startPosition = args[1].split(/\s/).filter(Boolean);
- var row = parseInt(startPosition[0]), col = parseInt(startPosition[1]);
- var matrix = new Array(rows);
- for (var i = 2; i < args.length; i += 1) {
- matrix[i - 2] = args[i].split('').filter(Boolean);
- }
- function movingToTheNextCell() {
- var cellValue = matrix[row][col];
- matrix[row][col] = undefined;
- switch (cellValue) {
- case 'l':
- row += 0;
- col += -1;
- break;
- case 'r':
- row += 0;
- col += 1;
- break;
- case 'u':
- row += -1;
- col += 0;
- break;
- case 'd':
- row += 1;
- col += 0;
- break;
- }
- return cellValue;
- }
- var sum = 0, countCells = 0;
- do {
- sum += (row * cols) + col + 1;
- if (matrix[row][col]) {
- movingToTheNextCell();
- } else {
- return console.log("lost %d", countCells);
- }
- countCells += 1;
- } while (row >= 0 && row < rows && col >= 0 && col < cols);
- console.log("out %d", sum);
- }
- solve([
- '3 4',
- '1 3',
- 'lrrd',
- 'dlll',
- 'rddd'
- ]);
- solve([
- '5 8',
- '0 0',
- 'rrrrrrrd',
- 'rludulrd',
- 'durlddud',
- 'urrrldud',
- 'ulllllll'
- ]);
- solve([
- '5 8',
- '0 0',
- 'rrrrrrrd',
- 'rludulrd',
- 'lurlddud',
- 'urrrldud',
- 'ulllllll'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement