Hello Programmers, In this post, you will know how to solve the HackerRank Encryption Solution. This problem is a part of the HackerRank Algorithms Series.
One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.
HackerRank Encryption Solution
Task
An English text needs to be encrypted using the following encryption scheme.
First, the spaces are removed from the text. Let L be the length of this text.
Then, characters are written into a grid, whose rows and columns have the following constraints:
[√L] <= row <= column <= [√L] , where [x] is the floor function and [x] is ceil function
Example
s = if man was meant to stay on the ground god would have given us roots
After removing spaces, the string is 54 characters long. √54 is between 7 and 8, so it is written in the form of a grid with 7 rows and 8 columns.
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
- Ensure that rows x columns >= L
- If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rows x columns.
The encoded message is obtained by displaying the characters of each column, with a space between column texts. The encoded message for the grid above is:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
Create a function to encode a message.
Function Description
Complete the encryption function in the editor below.
encryption has the following parameter(s):
- string s: a string to encrypt
Returns
- string: the encrypted string
Input Format
One line of text, the string s
Constraints
- 1 <= length of s <= 81
- s contains characters in the range ascii[a-z] and space, ascii(32).
Sample Input
haveaniceday
Sample Output 0
hae and via ecy
Explanation 0
L = 12, √12 is between 3 and 4.
Rewritten with 3 rows and 4 columns:
have
anic
eday
Sample Input 1
feedthedog
Sample Output 1
fto ehg ee dd
Explanation 1
L = 10, √10 is between 3 and 4.
Rewritten with 3 rows and 4 columns:
feed
thed
og
Sample Input 2
chillout
Sample Output 2
clu hlt io
Explanation 2
L = 8, √8 is between 2 and 3.
Rewritten with 3 columns and 3 rows (2 * 3 = 6 < 8 so we have to use 3 X 3.)
chi
llo
ut
HackerRank Encryption Solution
Encryption Solution in C
#include<stdio.h> #include<math.h> int main() { char s[82]; scanf("%s",s); int i,c,r,n,j,k,sq; for(i=0;s[i];++i); sq=sqrt(i); if(sq*sq==i) { c=r=sq; } else { r=sq;c=sq+1; if(r*c<i){r=sq+1;c=sq+1;} } for(j=0;j<c;++j) { for(k=0;k<r;++k)if(j+k*c<i)printf("%c",s[j+k*c]); printf(" "); } return 0; }
Encryption Solution in Cpp
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ #include <cstring> #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; #define MAXN 1000 char str[MAXN]; char res[MAXN][MAXN]; int gr,gc; int r,c; int main(){ scanf("%s",str); int len = strlen(str); int DIFF = 1<<20; int AREA = 1<<20; for(int i=1; i<=100; ++i) { if(i*i>=len) { r = i; c = i; break; } if(i*(i+1)>=len){ r = i; c = i+1; break; } } int id = 0; for(int i=0; i<MAXN; ++i) for(int j=0; j<MAXN; ++j) res[i][j] = '\0'; for(int i=0; i<r; ++i) for(int j=0; j<c; ++j) res[i][j] = str[id++]; for(int i=0; i<c; ++i) { for(int j=0; res[j][i]!='\0'; ++j) printf("%c",res[j][i]); printf(" "); } return 0; }
Encryption Solution in Java
import java.util.Scanner; public class Solution { /** * @param args */ public static void main(String[] args) { Scanner scan= new Scanner(System.in); String s= scan.next(); int wid,len; int l=s.length(); double f=Math.sqrt(l); int test=(int)f; if(test*test==l){ wid=test; len=test; }else{ wid=test; len=test+1; if(wid*len<l) wid++; } int a=0; char arr[][] = new char[wid][len]; for(int i=0;i<wid;i++){ for(int j=0;j<len;j++){ if(a==s.length()) arr[i][j]=' '; else arr[i][j]=s.charAt(a++); } if(a==s.length()) break; } String temp=""; boolean go=false; for(int i=0;i<len;i++){ for(int j=0;j<wid;j++){ if(!(arr[j][i]==' ')){ temp=temp+arr[j][i]; go=true; } } if(go) temp=temp+" "; go=false; } System.out.println(temp); } }
Encryption Solution in Python
from math import sqrt, ceil message = raw_input().strip() size = len(message) t1 = int(ceil(sqrt(size))) t2 = int(ceil(float(size)/t1)) rows = min(t1, t2) cols = max(t1, t2) cipher = [] while message: cipher.append(message[:cols]) message = message[cols:] for j in xrange(cols): tmp = [] for i in xrange(rows): try: tmp.append(cipher[i][j]) except IndexError: pass print ''.join(tmp),
Encryption Solution using JavaScript
function main(data) { var i, j, word, pos, result = [], col_count = Math.ceil(Math.sqrt(data.length)), row_count = Math.ceil(data.length / col_count); for (i = 0; i < col_count; ++i) { word = ''; for (j = 0; j < row_count; ++j ) { pos = col_count * j + i; if (pos < data.length) word += data[pos]; } result.push(word); } return result.join(' '); } var data = ''; process.stdin.resume(); process.stdin.setEncoding("ascii"); process.stdin.on("data", function (input) { data += input; }); process.stdin.on('end', function() { process.stdout.write(main(data.trim())); });
Encryption Solution in Scala
object Solution { def main(args: Array[String]) { println(encrypt(makeValves(Console.readLine)).mkString(" ")) } def getValveSize(data : String) : Int = { val size = Math.sqrt(data.length.toDouble) if(size.toInt.toDouble == size) size.toInt else size.toInt + 1 } def makeValves(data :String) : List[String] = { val valveSize = getValveSize(data) def _makeValves(_data:String, accu : List[String]) : List[String] = { if(_data.isEmpty) accu else _makeValves(_data.drop(valveSize), accu :+_data.take(valveSize)) } _makeValves(data, Nil) } def encrypt(input : List[String]) : List[String] ={ def encrypt0(_input : List[String],accu:List[String]) : List[String] = { val temp = _input.filterNot(_.isEmpty) if(temp.isEmpty) accu else encrypt0(temp.map(_.tail),accu :+ temp.map(_.head).mkString) } encrypt0(input,Nil) } }
Encryption Solution in Pascal
(* Enter your code here. Read input from STDIN. Print output to STDOUT *) program Encryption; uses math; var x,i,j,len,width:Longint; str:string; arr:array[0..10]of Longint; begin x:=1; arr[1]:=1; for i:=2 to 10 do begin x:=x+2; arr[i]:=arr[i-1]+x; end; ReadLn(str); len:=length(str); for i:=1 to 10 do if len<=arr[i] then begin width:=i; break; end; for i:=1 to width do begin for j:=0 to width-1 do if (i+ j*width )<= len then Write(str[i+ j*width]); Write(' '); end; WriteLn(); end.
Disclaimer: This problem (Encryption) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.