encryption hackerrank solution c 2b 2b

Solutions on MaxInterview for encryption hackerrank solution c 2b 2b by the best coders in the world

showing results for - "encryption hackerrank solution c 2b 2b"
Zahra
20 Jul 2018
1#include <algorithm>
2#include <cmath>
3#include <fstream>
4#include <iostream>
5#include <ostream>
6#include <string>
7using namespace std;
8
9string encryption(string& input) {    
10    input.erase(std::remove(input.begin(), input.end(), ' '), input.end());
11
12    int size = input.length();
13    int lowerbound = (int) floor(sqrt(size));
14    int upperbound = (int) ceil(sqrt(size));
15    int total = upperbound * lowerbound;
16    
17    while (total < size) {
18        if (lowerbound < upperbound) {
19            ++lowerbound;
20        } else {
21            ++upperbound;
22        }
23        total = upperbound * lowerbound;
24    }
25    
26    char grid[lowerbound][upperbound] = {0};
27    int index = 0;
28    
29    for (int row = 0; row < lowerbound; ++row) {
30        for (int col = 0; col < upperbound; ++col) {
31            if (index <= input.length() - 1) {
32                grid[row][col] = input.at(index);
33                ++index;
34            }
35        }
36    }
37    
38    string encrypted = "";
39    
40    for (int col = 0; col < upperbound; ++col) {
41        for (int row = 0; row < lowerbound; ++row) {
42            if (grid[row][col] != 0) {
43                encrypted += grid[row][col];
44            }
45        }
46        
47        if (col != upperbound - 1) {
48            encrypted += " ";
49        }
50    }
51    
52    return encrypted;
53}
54
55int main() {
56    ofstream fout(getenv("OUTPUT_PATH"));
57    string s;
58    
59    getline(cin, s);
60    string result = encryption(s);
61    fout << result << "\n";
62    fout.close();
63    return 0;
64}
65
similar questions
queries leading to this page
encryption hackerrank solution c 2b 2b