Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* We are given a matrix containing arrows that need to be moved. The arrows are the following: '<'
- (ASCII code 60), '>' (ASCII code 62), '^' (ASCII code 94), 'v' (ASCII code 118). Respectively pointing left,
- right, up and down. There are also blank spaces that are indicated by 'o' (ASCII code 111).
- There will be no other characters in the matrix.
- Your task is to move all arrows, one at a time, in the direction they point to until there are
- no more possible moves.
- The arrows should be moved in the following order: first the ones in the uppermost row and the leftmost column.
- Arrows cannot move if their way is blocked by other arrows or if they reach the end of the matrix.
- The only characters that will be present in the matrix will be '<', '>', '^', 'v' and 'o'.
- At the first input line you will be given a number n specifying how many rows after it will follow.
- At the next n lines you will be given the matrix with the arrows that need to be moved.
- The output should be the new matrix with all the arrows moved to the direction they're facing. */
- "use strict";
- function solve(args) {
- var rows = parseInt(args[0]);
- var cols = args[1].length;
- var countTurns = Math.max(rows, cols);
- var matrix = [];
- for (var i = 1; i < args.length; i += 1) {
- matrix[i - 1] = args[i].split('');
- }
- for (i = 0; i < countTurns; i += 1) {
- for (var row = 0; row < matrix.length; row += 1) {
- for (var col = 0; col < matrix[row].length; col += 1) {
- if (matrix[row][col] != 'o') {
- movingArrowToTheNextPosition();
- }
- }
- }
- }
- console.log(matrix);
- function movingArrowToTheNextPosition() {
- var arrow = matrix[row][col];
- switch (arrow) {
- case 'v':
- if (row + 1 < matrix.length && matrix[row + 1][col] == 'o') {
- matrix[row + 1][col] = arrow;
- matrix[row][col] = 'o';
- }
- break;
- case '^':
- if (row - 1 >= 0 && matrix[row - 1][col] == 'o') {
- matrix[row - 1][col] = arrow;
- matrix[row][col] = 'o';
- }
- break;
- case '<':
- if (col - 1 >= 0 && matrix[row][col - 1] == 'o') {
- matrix[row][col - 1] = arrow;
- matrix[row][col] = 'o';
- }
- break;
- case '>':
- if (col + 1 < matrix[row].length && matrix[row][col + 1] == 'o') {
- matrix[row][col + 1] = arrow;
- matrix[row][col] = 'o';
- }
- break;
- }
- }
- }
- solve([
- '3',
- 'voo<',
- 'oo>o',
- 'o^oo'
- ]);
- solve([
- '3',
- 'oov',
- 'oo<',
- 'oo^'
- ]);
- solve([
- '4',
- 'ooo<',
- 'oovo',
- '^ooo',
- 'oo^o'
- ]);
- solve([
- '5',
- '^voov',
- 'v<^<<',
- 'o<o<v',
- 'o^<^v',
- '>o>^o'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement