Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Your task is to calculate if Joro can escape from his mother, using the given sequence of jumps.
- You are given a field of size N x M where the values are as follows:
- On the first row the numbers are from 1 to M, on the second row – from M+1 to 2*M,
- on the third – from 2*M +1 to 3*M, etc…
- By given position in the field, and using the patterns given, calculate if Joro can escape from his mother.
- You are also given a sequence of jumps over the field. The jumps are described with change to the row and column,
- i.e. when on position (R, C) with jump (-2, 3), Joro will go to position (R-2, C+3).
- When the sequence of jumps is over, Joro must start from the start of the jumps sequence.
- If Joro goes outside the field, he has escaped, if Joro goes to a previously visited position, he is caught.
- Each of the string represents an integer sequence. The arguments are as follows:
- args[0] contains the numbers N, M and J. (J is number of jumps)
- args[1] contains the star position, R and C
- args[2] to args[2+J] contains the jumps.
- Your method should return a single string – “escaped SUM_OF_NUMBERS" or "caught NUMBER_OF_JUMPS". */
- "use strict";
- function solve(args) {
- var dimensions = args[0].split(/\s+/).filter(Boolean);
- var rows = parseInt(dimensions[0]), cols = parseInt(dimensions[1]), j = parseInt(dimensions[2]);
- var startPosition = args[1].split(/\s+/).filter(Boolean);
- var row = parseInt(startPosition[0]), col = parseInt(startPosition[1]);
- var directions = {};
- var i;
- for (i = 2; i < j + 2; i += 1) {
- args[i] = args[i].split(/\s+/).filter(Boolean);
- var rowValue = parseInt(args[i][0]);
- var colValue = parseInt(args[i][1]);
- var key = (i - 2).toString(10);
- directions[key] = [rowValue, colValue];
- }
- var matrix = new Array(rows);
- for (i = 0; i < matrix.length; i += 1) {
- matrix[i] = new Array(cols);
- for (var k = 0; k < cols; k += 1) {
- matrix[i][k] = true;
- }
- }
- var sum = 0;
- var jumpsNum = 0;
- do {
- sum += (row * cols) + col + 1;
- var index = parseInt(jumpsNum % j);
- if (matrix[row][col]) {
- moveToTheNextCell();
- } else {
- return console.log("caught " + jumpsNum);
- }
- jumpsNum += 1;
- } while (row >= 0 && row < rows && col >= 0 && col < cols);
- console.log("escaped " + sum);
- function moveToTheNextCell() {
- if (directions.hasOwnProperty(index)) {
- var rowAdd = directions[index][0];
- var colAdd = directions[index][1];
- var cellValue = matrix[row][col];
- matrix[row][col] = false;
- row += rowAdd;
- col += colAdd;
- }
- return cellValue;
- }
- }
- solve([
- '6 7 3',
- '0 0',
- '2 2',
- '-2 2',
- '3 -1'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement