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 constraint:
floor(sqrt(L]<=row<=column<=ceil(sqrt(L))
Example:
Input: s = "haveaniceday"
Output: hae and via ecy
Approach
Java
import java.util.Vector;public class Encryption {public static void main(String[] args) {String s = "haveaniceday";int n = 0;for (int i = 0; i < s.length(); i++) {if (s.charAt(i) != ' ') {n++;}}int row = (int) Math.sqrt(n);int col = row + 1;if (row * row == n)col = row;while (row * col < n) {if (row < col)row++;elsecol++;if (row * col >= n)break;}int l = 0;char grid[][] = new char[row][col];Vector<String> v = new Vector<>();for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {while (l < n && s.charAt(l) == ' ')l++;if (l != n)grid[i][j] = s.charAt(l++);elsegrid[i][j] = '-';}}for (int i = 0; i < col; i++) {String str = "";for (int j = 0; j < row; j++) {if (grid[j][i] != '-')str += grid[j][i];}v.add(str);}for (int i = 0; i < v.size(); i++)System.out.print(v.get(i) + " ");}}
C++
#include <bits/stdc++.h>using namespace std;int main(){string s = "haveaniceday";int n = 0;for (int i = 0; i < s.size(); i++){if (s[i] != ' '){n++;}}int row = sqrt(n);int col = row + 1;if (row * row == n)col = row;while (row * col < n){if (row < col)row++;elsecol++;if (row * col >= n)break;}int l = 0;char grid[row][col];vector<string> v;for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){while (l < n && s[l] == ' ')l++;if (l != n)grid[i][j] = s[l++];elsegrid[i][j] = '-';}}for (int i = 0; i < col; i++){string str = "";for (int j = 0; j < row; j++){if (grid[j][i] != '-')str += grid[j][i];}v.push_back(str);}for (int i = 0; i < v.size(); i++)cout << v[i] << " ";return 0;}
No comments:
Post a Comment