Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Calculate a width
and height
of a required matrix:
height = ceil(length(input_string)
width = floor(length(input_string)
Then create a height x width
matrix containing a characters from input_string
. Transpose the matrix and print all rows.
Node: Instead we can print all columns of the prepared matrix. For 2 characters i
and j
in the input_string
holds that they are in the same column if i mod height = j mod height
.
I created solution in 4 languages:
All solutions are also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 10 |
import scala.collection.immutable.TreeMap object Encryption extends App { val input = io.Source.stdin.bufferedReader().readLine() val height = Math.ceil(Math.sqrt(input.length)) val width = Math.floor(Math.sqrt(input.length)) val groupByColumn = TreeMap(input.indices.toList.groupBy(_ % height).toArray:_*).values val encrypted = groupByColumn.map(_.map(input.charAt).mkString("")).mkString(" ") println(encrypted) } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Scanner; public class Encryption { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); String input = stdin.nextLine(); int height = (int) Math.ceil(Math.sqrt(input.length())); int width = (int) Math.floor(Math.sqrt(input.length())); StringBuilder result = new StringBuilder(); for(int i = 0; i < height; i++) { int j = i; while(j < input.length()) { result.append(input.charAt(j)); j += height; } result.append(' '); } System.out.println(result); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function processData(input) { var height = parseInt(Math.ceil(Math.sqrt(input.length)), 10); var width = parseInt(Math.floor(Math.sqrt(input.length)), 10); var result = ''; for(var i = 0; i < height; i++) { var j = i; while(j < input.length) { result += input[j]; j += height; } result += ' '; } console.log(result); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
input = gets.chomp width = Math.sqrt(input.length).floor height = Math.sqrt(input.length).ceil result = "" for i in 0...height do j = i while j < input.length result += input[j] j += height end result += " " end puts result |