-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathsimple-encryption-in-java.java
More file actions
91 lines (77 loc) · 2.1 KB
/
simple-encryption-in-java.java
File metadata and controls
91 lines (77 loc) · 2.1 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Problem Link : https://www.hackerrank.com/challenges/encryption/problem
/*
An English text needs to be encrypted using the following encryption scheme.
First, the spaces are removed from the text. Let be the length of this text.
For example, the sentence
"s = if man was meant to stay on the ground god would have given us roots"
after removing spaces is characters long. is between and,
so it is written in the form of a grid with 7 rows and 8 columns.
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
Sample Input 0 : have a nice day
Sample Output 0 : hae and via ecy
Sample Input 1 : feed the dog
Sample Output 1 : fto ehg ee dd
*/
import java.lang.*;
public class SimpleEncryption {
static String encryption(String s) {
int length = s.length();
double sqrt = Math.sqrt(length);
double floor = Math.floor(sqrt);
double ceil = Math.ceil(sqrt);
while(!((floor * ceil) >= length)) {
if(floor > ceil) {
ceil++;
} else {
floor++;
}
}
int row = (int) floor;
int col = (int) ceil;
char[] chr = s.toCharArray();
char[][] arr = new char[row][col];
int k = 0;
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
if(!(k >= length)) {
arr[i][j] = chr[k++];
} else {
continue;
}
}
}
int total = (row+1)*(col+1);
char[] fnl = new char[total];
k = 0;
for(int j=0;j<col;j++) {
for(int i=0;i<row;i++){
if(! (arr[i][j] == '\0')) {
if (!(k == total)) {
fnl[k++] = arr[i][j];
}
}
}
if(! (k==total)) {
fnl[k++] = ' ';
}
}
for(int i=0;i<total;i++) {
if(fnl[i] == '\0') {
fnl[i] = ' ';
}
}
String res = new String(fnl);
res = res.trim();
return res;
}
public static void main(String[] args) {
System.out.println(encryption("feedthedog"));
System.out.println(encryption("haveaniceday"));
}
}