-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMessage Encryption.java
More file actions
60 lines (51 loc) · 1.44 KB
/
Message Encryption.java
File metadata and controls
60 lines (51 loc) · 1.44 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
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input string and column count
String s = sc.nextLine().trim();
int c = sc.nextInt();
sc.close();
// Convert the string into a character array
char[] chars = s.toCharArray();
int rows = chars.length / c;
// Create the matrix to store characters
char[][] m = new char[rows][c];
int index = 0;
// Fill the matrix row by row
for (int i = 0; i < rows; i++) {
for (int j = 0; j < c; j++) {
m[i][j] = chars[index++];
}
}
// Reverse the characters in even rows (1-based index)
for (int i = 1; i < rows; i += 2) {
for (int j = 0, k = c - 1; j < k; j++, k--) {
char temp = m[i][j];
m[i][j] = m[i][k];
m[i][k] = temp;
}
}
// Collect the result by traversing column-wise
StringBuilder result = new StringBuilder();
for (int j = 0; j < c; j++) {
for (int i = 0; i < rows; i++) {
result.append(m[i][j]);
}
}
// Print the final result
System.out.println(result.toString());
}
}
Example 1:
Input:
midinadiazne
3
Output:
madeinindiaz
Example 2:
Input:
loaesfbnaiordilertenrdhdw
5
Output:
lionroaredandthebirdsflew