|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | + |
| 5 | +process.stdin.resume(); |
| 6 | +process.stdin.setEncoding('utf-8'); |
| 7 | + |
| 8 | +let inputString = ''; |
| 9 | +let currentLine = 0; |
| 10 | + |
| 11 | +process.stdin.on('data', inputStdin => { |
| 12 | + inputString += inputStdin; |
| 13 | +}); |
| 14 | + |
| 15 | +process.stdin.on('end', _ => { |
| 16 | + inputString = inputString.replace(/\s*$/, '') |
| 17 | + .split('\n') |
| 18 | + .map(str => str.replace(/\s*$/, '')); |
| 19 | + |
| 20 | + main(); |
| 21 | +}); |
| 22 | + |
| 23 | +function readLine() { |
| 24 | + return inputString[currentLine++]; |
| 25 | +} |
| 26 | +function getMatrixDimension(s) { |
| 27 | + let len = Math.floor(Math.sqrt(s.length)); |
| 28 | + let m = len; |
| 29 | + let n = len + 1; |
| 30 | + if ((m * n) < s.length) { |
| 31 | + m = n = len + 1; |
| 32 | + } |
| 33 | + else if (Math.sqrt(s.length) % 1 === 0) { |
| 34 | + m = n = Math.sqrt(s.length); |
| 35 | + } |
| 36 | + return [m, n]; |
| 37 | +} |
| 38 | +// Complete the encryption function below. |
| 39 | +function encryption(s) { |
| 40 | + let [m, n] = getMatrixDimension(s); |
| 41 | + let strindex = 0; |
| 42 | + let grid = []; |
| 43 | + for (let i = 0; i < m; i++) { |
| 44 | + grid[i] = []; |
| 45 | + for (let j = 0; j < n; j++) { |
| 46 | + grid[i][j] = s[strindex] || ''; |
| 47 | + strindex++; |
| 48 | + } |
| 49 | + } |
| 50 | + let out = ""; |
| 51 | + for (let i = 0; i < n; i++) { |
| 52 | + for (let j = 0; j < m; j++) { |
| 53 | + out += grid[j][i]; |
| 54 | + } out += " "; |
| 55 | + } |
| 56 | + return out; |
| 57 | +} |
| 58 | + |
| 59 | +function main() { |
| 60 | + const ws = fs.createWriteStream(process.env.OUTPUT_PATH); |
| 61 | + |
| 62 | + const s = readLine(); |
| 63 | + |
| 64 | + let result = encryption(s); |
| 65 | + |
| 66 | + ws.write(result + "\n"); |
| 67 | + |
| 68 | + ws.end(); |
| 69 | +} |
0 commit comments