Advertisement
dimipan80

Exams - Reveal Triangles

Nov 23rd, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given a sequence of text lines, holding small Latin letters. Your task is to reveal all triangles
  2. in the text by changing their letters with '*'. Triangles consist of equal letters in the form of triangle.
  3.  Triangles can span different sizes: 2 lines, 3 lines, 4 lines, etc. Triangles can overlap (some letters
  4.  can take part in several triangles). Print at the console the input data after replacing all triangles by '*'. */
  5.  
  6. "use strict";
  7.  
  8. function revealTriangles(arr) {
  9.     for (var i = 0; i < arr.length; i += 1) {
  10.         arr[i] = arr[i].split('').filter(Boolean);
  11.     }
  12.  
  13.     function clone(obj) {
  14.         var deepCopyObj = new obj.constructor();
  15.         for (var property in obj) {
  16.             if (obj.hasOwnProperty(property)) {
  17.                 switch (typeof obj[property]) {
  18.                     case 'object':
  19.                         deepCopyObj[property] = clone(obj[property]);
  20.                         break;
  21.                     default:
  22.                         deepCopyObj[property] = obj[property];
  23.                         break;
  24.                 }
  25.             }
  26.         }
  27.  
  28.         return deepCopyObj;
  29.     }
  30.     var output = clone(arr);
  31.  
  32.     for (var row = 0; row < arr.length; row += 1) {
  33.         for (var col = 0; col < arr[row].length; col += 1) {
  34.             if (row + 1 < arr.length && col - 1 >= 0 && col + 1 < arr[row + 1].length &&
  35.                 arr[row][col] == arr[row + 1][col - 1] && arr[row][col] == arr[row + 1][col] &&
  36.                 arr[row][col] == arr[row + 1][col + 1]) {
  37.                 output[row][col] = '*';
  38.                 output[row + 1][col - 1] = '*';
  39.                 output[row + 1][col] = '*';
  40.                 output[row + 1][col + 1] = '*';
  41.             }
  42.         }
  43.         output[row] = output[row].join('');
  44.     }
  45.     return output.join('\n');
  46. }
  47.  
  48. console.log(revealTriangles([
  49.     'abcdexgh',
  50.     'bbbdxxxh',
  51.     'abcxxxxx'
  52. ]));
  53.  
  54. console.log(revealTriangles([
  55.     'aa',
  56.     'aaa',
  57.     'aaaa',
  58.     'aaaaa'
  59. ]));
  60.  
  61. console.log(revealTriangles([
  62.     'ax',
  63.     'xxx',
  64.     'b',
  65.     'bbb',
  66.     'bbbb'
  67. ]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement