# Encryption – HackerRank Solution

In this post, we will solve Encryption HackerRank Solution. This problem (Encryption) is a part of HackerRank Algorithms series.

Contents

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 0

``haveaniceday``

Sample Output 0

ValueImpression Mobile Ads === codingbroz.com_300x250 (#88863) ===
=== codingbroz.com_300x250 (#88863) ===
``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.)

## Solution – Encryption – HackerRank Solution

### C++

```#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;
}
```

### Python

```#!/bin/python3

import sys
from math import sqrt
from math import ceil

def get_grid(number):
root = sqrt(number)

x = int(root//1)
y = ceil(root)

while x*y < number:
if x <= y:
x += 1
else:
y += 1

return (x, y)

def encryption(string):
string = string.strip().replace(' ', '')
str_len = len(string)

x, y = get_grid(str_len)
#print("x = {} y = {}".format(x, y))
grid = [ [ '' for i in range(x) ] for _j in range(y) ]

count = 0
x_ind = 0
y_ind = 0
for ind in range(str_len):
if count / y == 1 and count % y == 0:
count = 0
y_ind += 1
x_ind = 0

grid[x_ind][y_ind] = string[ind]
count += 1
x_ind += 1

#print(grid)
out = ''
for _i in range(y):
for _j in range(x):
out += grid[_i][_j]
out += ' '
#print(out)

#out = ''
#for _i in range(y):
#    for _j in range(x):
#        out += grid[_i][_j]
#    out += ' '

return out

if __name__ == "__main__":
s = input().strip()
result = encryption(s)
print(result)
```

### Java

```import java.util.Scanner;

public class Solution {

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);
}

}
```

Note: This problem (Encryption) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.