Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a matrix of directions. The rows are zero-based. The possible directions are four:
- • "dr" stands for "down-right" direction
- • "ur" stands for "up-right" direction
- • "ul" stands for "up-left" direction
- • "dl" stands for "down-left" direction
- You should generate another matrix with the same size. The numbers in each row are consecutive.
- The leftmost (first) number in each row is a power of 2, calculated with the formula 2row where row is the number
- of this row. Your task is to find the sum that can be found, using the given directions and summing the numbers
- in each cell you step into. If with the current direction, you step out of the matrix – print "successed with SUM",
- where sum is the calculated sum. If you step on a cell, that you have previously stepped in – print
- "failed at POSITION", where POSITION is the position of the previously visited cell.
- You start always at position (0, 0) – row = 0, column = 0. Create a function in JavaScript that solves this problem.
- The first value of the input arguments you will be the numbers R and C, separated by a space
- • R is the number of rows in the matrix
- • C is the number of columns in the matrix
- The next R values in the input arguments will be exactly C directions, separated by a space.
- Your function should return a single string:
- • If success, return "successed with SUM", where sum is the sum of the visited cells
- • If fail, return "failed at POSITION", where POSITION is the position of the already visited cell */
- "use strict";
- function solve(args) {
- args[0] = args[0].split(/\s+/).filter(Boolean);
- var rows = parseInt(args[0][0]);
- var cols = parseInt(args[0][1]);
- var matrix = new Array(rows);
- for (var i = 1; i < args.length; i += 1) {
- matrix[i - 1] = args[i].split(/\s+/).filter(Boolean);
- }
- var sum = 0;
- var row = 0;
- var col = 0;
- function movingToTheNextCell() {
- var cellValue = matrix[row][col];
- matrix[row][col] = undefined;
- switch (cellValue) {
- case 'dr':
- row += 1;
- col += 1;
- break;
- case 'dl':
- row += 1;
- col += -1;
- break;
- case 'ur':
- row += -1;
- col += 1;
- break;
- case 'ul':
- row += -1;
- col += -1;
- break;
- }
- return cellValue;
- }
- do {
- sum += (Math.pow(2, row) + col);
- if (matrix[row][col]) {
- movingToTheNextCell();
- } else {
- return console.log("failed at (%d, %d)", row, col);
- }
- } while (row >= 0 && row < rows && col >= 0 && col < cols);
- console.log("successed with %d", sum);
- }
- solve([
- '3 5',
- 'dr ur dr ul dr',
- 'dr ur dr dl dr',
- 'dr ur dr ul dr'
- ]);
- solve([
- '3 5',
- 'dr ur dr ul dr',
- 'dr ur dr dl dr',
- 'dr ur ur ul dr'
- ]);
- solve([
- '3 5',
- 'dr dl dr ur ul',
- 'dr dr ul ur ur',
- 'dl dr ur dl ur'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement